PHP: Array Basics

, , …,

List in PHP is called array. Each element is actually a pair, made of a “key” and a “value”. The “key” can be omitted if you don't need a list of pairs. If a key is omitted, they are automatically generated using incremental indexes starting from 0.

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 Tutorial.

Array is constructed using this form “array()”. Here's a simple example:

<?php
$x = array(7,2,3,"yes",5);
print_r($x);
?>

Getting

Length

Use “count()” function to get the number of elements.

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

Getting A Element

Extracting element can be done by this form “$arr[key]”.

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

Changing

Replacing A Element

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

Appending A Element

Adding a element is done by the form “$arr[newKey]=val”. The “newKey” must be a key that does not exist already, otherwise it simply replace that key's value.

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);
?>

Removing Elements

To delete a element, use “unset()”.

<?php
$x = array(7,"yes",5);
unset($x[1]); // removes the "yes"
print_r($x); // 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);
?>

To get a element from a nested array, use the form “$arr[key1][key2][…]…”. Example:

<?php
$x = array(7,"yes",5);
$y = array("woot", $x, "wee");
echo $y[1][0]; // prints 7
?>
blog comments powered by Disqus
2007-11