PHP: Array

By Xah Lee. Date: . Last updated: .

What is PHP Array

PHP array is a ordered list of pairs. Each pair, is a key and a value.

The key can be omitted, and if so, it is automatically given keys of 0, 1, 2, etc.

PHP array, combines the concept of list and map into one.

This page shows array as simple list without using the key.

For using array as a keyed-list (aka hash-table, dictionary, associative list), see PHP: Hash Table .

Creating Array

array()

<?php
$x = array(7,2,3);
print_r($x);
# Array ( [0] => 7 [1] => 2 [2] => 3 )
?>

Length

count()

<?php
$x = array(7,"yes",5);
echo count($x);
# 3
?>

Getting A Element

$arr[key]

<?php
$x = array(7,2,3,"yes",5);
echo $x[1];
# 2
?>

Replacing A Element

<?php
$x = array(7,"yes",5);
$x[1] = "no";
echo $x[1];
# no
?>

Appending A Element

Adding a element is done by the form

$arr[newKey]=val

if newKey exist, its value is replaced.

If you are using array as simple list without keys, and have never removed any element in your list, you can add new ones with automatic index like this:

$myList[]=newVal

<?php
$x = array("nil", "bi", "tri");
$x[]="quad";
print_r($x);
# Array ( [0] => nil [1] => bi [2] => tri [3] => quad )
?>

Removing Elements

unset()

<?php
$x = array(7,"yes",5);

# removes the "yes"
unset($x[1]);

print_r($x);
# Array ( [0] => 7 [2] => 5 )

# element with index 1 no longer exist.
?>

🛑 WARNING: Once a element is deleted, there no longer exist a element with that element's index. In other words, the array is not re-indexed, and in fact there is no such concept as re-indexing. If you want the index to be sequential starting from 0 again, just create a copy like this:

$newA = array_values($oldA);

Nested List

Arrays can be nested arbitrarily.

<?php
$x = array(7,"yes",5);
$y = array("woot", $x, "wee");
print_r($y);
# Array ( [0] => woot [1] => Array ( [0] => 7 [1] => yes [2] => 5 ) [2] => wee )
?>

To get a element from a nested array, use the form

$arr[key1][key2][…]…

<?php
$x = array(7,"yes",5);
$y = array("woot", $x, "wee");
echo $y[1][0];
# 7
?>

PHP, Data Structure