A PHP array allows us to store and process a series of data or values. Using an array, an application can conveniently perform a common task (or tasks) on the entire series.
PHP provides two types of arrays: indexed and associative. In indexed arrays, elements are stored and accessed using an integer index. In associative arrays, elements are stored and accessed using keys. For both of these arrays, their elements do not necessarily have to be of the same type!
PHP arrays (both indexed and associative) offer flexibility for dynamically adding and deleting array elements. This flexibility is not found in several high-level languages like C, where we need to explicitly define an array and provide its size. For using a variable-size array in C, we require advanced mechanisms of memory allocation (malloc) and pointers; PHP offers variable size arrays without using any of these advanced mechanisms!
An indexed array uses an index to identify these elements; the first element has an index of 0, the second element has an index of 1, and in the end, the last element has an index of (N-1). These indexes allow us to easily navigate and update values stored in these elements.
The below figure shows an indexed array ($array_userid) that has N elements.
$array_userid[1] $array_userid[N-1] | | | | V V -------------------------------------------------------------------- | "jwayne" | "kmoore" | "msimpson" | "hjones" | ... | "jfulton" | --------------------------------------------------------------------- ^ | | $array_userid[0] Figure: An Indexed Array with N elements
To use an array, we can specify the name and the size of the array before we start using it. Thus, "$array_userid[1000]" means that we define an array, $array_userid, that can hold 1000 values. After this definition, we are all set to use this array.
However, PHP is flexible and if we want, we can skip providing name and size of the array! Instead, we can just start using the array as need arises and PHP would automatically keep track of the array (and will create one, if the array does not exist!). Further, we can add elements to the array as need arises and PHP would automatically increase the size of the array.
If need arises, we can use unset() method to delete an element from an array. Please note that unset() works with non-array elements as well.
We provide a small program below to introduce PHP indexed arrays. First, we declare "$array_userid[3]" to say that $array_userid is an array of 3 elements. Then, we assign values to each of the elements. Once values are assigned, we use print_R to print these elements. Next, we provide $array_userid2 to demonstrate PHP's flexibility and add elements to it as and when needed. This program also uses unset() method to delete some of the array elements.
<?php /* Let us define an array and assign elements to it */ $array_userid1[3]; $array_userid1[] = "jwayne"; $array_userid1[] = "kmoore"; $array_userid1[] = "msimpson"; echo "Printing array_userid1: <br>"; print_r($array_userid1); /* Let us add some elements to it on the fly */ $array_userid1[3] = "hjones"; $array_userid1[4] = "jfulton"; $array_userid1[5] = "arichter"; echo "<br><br>Printing array_userid1 after adding more elements: <br>"; print_r($array_userid1); /* Let us delete some elements on the fly */ unset($array_userid1[4]); unset($array_userid1[5]); echo "<br><br>Printing array_userid1 after deleting some elements: <br>"; print_r($array_userid1); /* Let us create a new array in a flexible manner */ $array_userid2[] = "jwayne"; $array_userid2[] = "kmoore"; $array_userid2[] = "msimpson"; echo "<br><br>Printing a new array, array_userid2: <br>"; print_r($array_userid2); ?>
To run this program, let us first store this file (let us name it "array.php") at a location that is accessible to the web server (in Fedora/Red Hat Linux, the default location for web server is "/var/www/html/"). Next, we need to ensure that the web server itself is running (in Fedora/Red Hat Linux, we can use "service httpd status" to see if the web server is running). When we load this file from a browser as "http://localhost/array.php", we would see the following output on the web server.
Printing array_userid1: Array ( [0] => jwayne [1] => kmoore [2] => msimpson ) Printing array_userid1 after adding more elements: Array ( [0] => jwayne [1] => kmoore [2] => msimpson [3] => hjones [4] => jfulton [5] => arichter ) Printing array_userid1 after deleting some elements: Array ( [0] => jwayne [1] => kmoore [2] => msimpson [3] => hjones ) Printing a new array, array_userid2: Array ( [0] => jwayne [1] => kmoore [2] => msimpson )
The output confirms that even though we did not formally define $array_userid2 before starting to use it, this array is still identical to $array_userid1.
Sometimes, it is more convenient to define an array and also assign initial values to it in the definition itself. We can easily do that as: "$array_userid = array("jwayne", "ksimon", "msimpson", "hjones", "jfulton");".
The $array_userid from the earlier program, has all the elements stored in one row; such arrays are often referred to as one-dimensional arrays. PHP also provides multi-dimensional indexed arrays that can hold more than one row of data.
Let us see an example.
$array_userid[0,1] $array_userid[0,N-1] $array_userid[0,0] | | | | | | | | V V V ------------------------------------------------------------------------------------ | "jwayne" | "ksimon" | "msimpson" | "hjones" | ... | "jfulton" | - --- - --- - --- - --- - --- - --- - |"James Wayne"|"Karuna Simon"|"Mark Simpson"|"Henry Jones"| ... |"James Fulton"| ------------------------------------------------------------------------------------ ^ ^ ^ | | | | | | $array_userid[1,0] | | $array_userid[1,1] $array_userid[1,N-1] Figure: A 2-dimensional indexed array with 2N elements
The above figure extends the earlier our example of $array_userid array to a 2-dimensional indexed array. With a 2-dimensional arrays, the index to locate an element has now two values: the first index value represents the row and the second index value represents the column. Thus, $array_userid[1,0] represents the value stored at row 1 and column 0. There is no limit to the number of rows (dimensions). Also, it is not necessary that all rows of the array should have the same number of columns!
Similar to one-dimensional arrays, PHP provides flexible ways to define multi-dimensional arrays as well and we can add a row to a multi-dimensional array in several ways.
Let us understand multi-dimensional array using a simple program. This program (provided below) redefines the array as "$array_user1[2][2]". This new definition means that the array has 2 rows, each with 2 elements -- thus, the total number of elements now is 4. For each row of $array_user1, the first column stores unique user IDs and the second column stores the name of these users. Alternatively, we do need to define the array first and we can start using (e.g. $array_user2) on the fly.
<?php function print_array ($var_array) { echo "<br>The length of the passed array is " . count($var_array). " <br>"; for ($counter=0; $counter < count($var_array); $counter++) { echo "Userid: {$var_array[$counter][0]} (index: [$counter,0]) "; echo "Username: {$var_array[$counter][1]} (index: [$counter,1])<br>"; } } /* Let us define a two-dimensional array */ $array_user1[2][2]; $array_user1[] = array("jfulton", "James Fulton"); $array_user1[] = array(1002, 100210021002.2323); var_dump($array_user1); echo "<br>Printing array_userid1"; print_array($array_user1); /* Let us add some elements to it on the fly*/ $array_user1[2][0] = "amoore"; $array_user1[2][1] = "Amanda Moore"; $array_user1[3] = array("hjones", "Henry Jones"); echo "<br>Printing array_userid1 after adding more elements"; print_array($array_user1); /* Let us delete some elements on the fly */ unset($array_user1[2]); unset($array_user1[3]); echo "<br>Printing array_userid1 after deleting some elements"; print_array($array_user1); /* Let us create a new two-dimensional array in a flexible manner */ $array_user2[] = array("jfulton", "James Fulton"); $array_user2[] = array(1002, 100210021002.2323); echo "<br>Printing array_userid2"; print_array($array_user2); ?>
We provide the output as below and print both userid and name of each user. The output of the var_dump() functions shows that the array passed has 2 elements (rows) and each of these elements are array in themselves. Also, please note that for the third row, we pass a float type as a name to demonstrate that elements of a PHP array do not necessarily have to be of the same type.
array(2) { [0]=> array(2) { [0]=> string(7) "jfulton" [1]=> string(12) "James Fulton" } [1]=> array(2) { [0]=> int(1002) [1]=> float(100210021002.23) } } Printing array_user1 The length of the passed array is 2 Userid: jfulton (index: [0,0]) Username: James Fulton (index: [0,1]) Userid: 1002 (index: [1,0]) Username: 100210021002.23 (index: [1,1]) Printing array_user1 after adding more elements The length of the passed array is 4 Userid: jfulton (index: [0,0]) Username: James Fulton (index: [0,1]) Userid: 1002 (index: [1,0]) Username: 100210021002.23 (index: [1,1]) Userid: amoore (index: [2,0]) Username: Amanda Moore (index: [2,1]) Userid: hjones (index: [3,0]) Username: Henry Jones (index: [3,1]) Printing array_user1 after deleting some elements The length of the passed array is 2 Userid: jfulton (index: [0,0]) Username: James Fulton (index: [0,1]) Userid: 1002 (index: [1,0]) Username: 100210021002.23 (index: [1,1]) Printing array_user2 The length of the passed array is 2 Userid: jfulton (index: [0,0]) Username: James Fulton (index: [0,1]) Userid: 1002 (index: [1,0]) Username: 100210021002.23 (index: [1,1])
Associative arrays make the concept of arrays more usable. This class of arrays provide indexing based on a keyword instead of an integer and thus, store a (key, value) pair instead of the traditional (index,value) storage. Since, we can access a value based on its key, these arrays are similar to hash tables.
array_user['name'] array_user['zip'] array_user['city'] | | | | | | V V V ----------------------------------------------------- Keys: | 'name' | 'zip' | 'city' | - ---- - ---- - --- - Values: | jwayne | 10110 | Palo Alto | ----------------------------------------------------- Figure: An Associative Array
The above figure presents an associative array with 3 key/value pair. Instead of referring to the elements using {0,1,2} indexes, we now refer to them using {'name','zip','city'} keys. Thus, array_user['name'] would evaluate to "jwayne".
Like indexed arrays, associative arrays are also flexible in terms of adding and deleting elements dynamically.
Similar to indexed arrays, PHP allows us to define multi-dimensional associative arrays as well. With a multi-dimensional associative array, the value of a key is yet another associative array.
Let us use a simple program (provided below) to demonstrate associative arrays. We start with two associative arrays, $array_user1 and $array_user2; these arrays store information about two users using keys, 'name', 'zip', and 'city'. If we have to retrieve the value of any key, then all we have to do is simply pass the key instead of index, e.g. "$array_user1['name']". We define a 2-dimensional associative array that holds these two associative arrays using two new keys ($array_associative_users).
<?php /* Let us define an associative array */ $array_user1 = array('name' => "jwayne", 'zip' => 10110, 'city' => "Palo Alto"); echo "Let us print array_user1: <br>"; print_r($array_user1); echo "<br><br> The value of user_name is ", $array_user1['name'], "<br><br>"; $array_user2 = array('name' => "amoore", 'zip' => 30030); echo "Let us print array_user2: <br>"; print_r($array_user2); echo "<br><br>"; /* Let us add some elements to it on the fly */ echo "Let us print array_user2 after adding some more elements: <br>"; $array_user2['city'] = "Arlington"; $array_user2['hobby'] = "whale-watching"; print_r($array_user2); echo "<br><br>"; /* Let us define an associative array to hold earlier associative arrays */ $array_associative_users = array('user1' => $array_user1, 'user2' => $array_user2); echo "Let us print array_associative_users: <br>"; print_r($array_associative_users); ?>
Here is the output of the above program. Unlike indexed arrays, print_r() prints key/value pairs for associative arrays instead of index/value pairs. Further, like indexed arrays, we can also add elements to the array on the fly -- the above program adds two new key/value pairs to $array_user2 after its initial definition.
Let us print array_user1 Array ( [name] => jwayne [zip] => 10110 [city] => Palo Alto ) The value of user_name is jwayne Let us print array_user2 Array ( [name] => amoore [zip] => 30030 ) Let us print array_user2 after adding some more elements Array ( [name] => amoore [zip] => 30030 [city] => Arlington [hobby] => whale-watching ) Let us print array_associative_users Array ([user1] => Array ( [name] => jwayne [zip] => 10110 [city] => Palo Alto ) [user2] => Array ( [name] => amoore [zip] => 30030 [city] => Arlington [hobby] => whale-watching))