Php Arrays

Introduction==

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, dictionary, list (vector), queue, hash table (an implementation of a map), collection, stack, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Syntax Specifying with array:

An array can be created by the array language construct. It takes as parameters any number of comma-separated key => value pairs. array( key =>  value    , ...     ) // key may only be an integer or string // value may be any value of any type Example:  "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12];   // 1 ?>

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string subscripts(indices).

A value can be of any PHP data type.

Note:

Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.

 array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6];   // 5 echo $arr["somearray"][13];  // 9 echo $arr["somearray"]["a"]; // 42 ?>

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.  43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> Warning: Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0. Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets. Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type. Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset function on it.  1, 12 => 2); $arr[] = 56;   // This is the same as $arr[13] = 56; // at this point of the script

$arr["x"] = 42; // This adds a new element to               // the array with key "x" unset($arr[5]); // This removes the element from the array

unset($arr);   // This deletes the whole array ?>

Note:

As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).

Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:  $value) { unset($array[$i]); }  print_r($array); // Append an item (note that the new key is 5, instead of 0). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?>

Useful functions: array_change_key_case — Changes all keys in an array array_chunk — Split an array into chunks array_combine — Creates an array by using one array for keys and another for its values array_count_values — Counts all the values of an array array_diff_assoc — Computes the difference of arrays with additional index check array_diff_key — Computes the difference of arrays using keys for comparison array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison array_diff — Computes the difference of arrays array_fill_keys — Fill an array with values, specifying keys array_fill — Fill an array with values array_filter — Filters elements of an array using a callback function array_flip — Exchanges all keys with their associated values in an array array_intersect_assoc — Computes the intersection of arrays with additional index check array_intersect_key — Computes the intersection of arrays using keys for comparison array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison array_intersect — Computes the intersection of arrays array_key_exists — Checks if the given key or index exists in the array array_keys — Return all the keys or a subset of the keys of an array array_map — Applies the callback to the elements of the given arrays array_merge_recursive — Merge two or more arrays recursively array_merge — Merge one or more arrays array_multisort — Sort multiple or multi-dimensional arrays array_pad — Pad array to the specified length with a value array_pop — Pop the element off the end of array array_product — Calculate the product of values in an array array_push — Push one or more elements onto the end of array array_rand — Pick one or more random entries out of an array array_reduce — Iteratively reduce the array to a single value using a callback function array_replace_recursive — Replaces elements from passed arrays into the first array recursively array_replace — Replaces elements from passed arrays into the first array array_reverse — Return an array with elements in reverse order array_search — Searches the array for a given value and returns the corresponding key if successful array_shift — Shift an element off the beginning of array array_slice — Extract a slice of the array array_splice — Remove a portion of the array and replace it with something else array_sum — Calculate the sum of values in an array array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function array_udiff — Computes the difference of arrays by using a callback function for data comparison array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions array_uintersect — Computes the intersection of arrays, compares data by a callback function array_unique — Removes duplicate values from an array array_unshift — Prepend one or more elements to the beginning of an array array_values — Return all the values of an array array_walk_recursive — Apply a user function recursively to every member of an array array_walk — Apply a user function to every member of an array array — Create an array arsort — Sort an array in reverse order and maintain index association asort — Sort an array and maintain index association compact — Create array containing variables and their values count — Count all elements in an array, or something in an object current — Return the current element in an array each — Return the current key and value pair from an array and advance the array cursor end — Set the internal pointer of an array to its last element extract — Import variables into the current symbol table from an array in_array — Checks if a value exists in an array key — Fetch a key from an array krsort — Sort an array by key in reverse order ksort — Sort an array by key list — Assign variables as if they were an array natcasesort — Sort an array using a case insensitive "natural order" algorithm natsort — Sort an array using a "natural order" algorithm next — Advance the internal array pointer of an array pos — Alias of current prev — Rewind the internal array pointer range — Create an array containing a range of elements reset — Set the internal pointer of an array to its first element rsort — Sort an array in reverse order shuffle — Shuffle an array sizeof — Alias of count sort — Sort an array uasort — Sort an array with a user-defined comparison function and maintain index association uksort — Sort an array by keys using a user-defined comparison function usort — Sort an array by values using a user-defined comparison function

Note:

The unset function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values function.

 'one', 2 => 'two', 3 => 'three'); unset($a[2]); /* will produce an array that would have been defined as  $a = array(1 => 'one', 3 => 'three'); and NOT $a = array(1 => 'one', 2 =>'three'); */ $b = array_values($a); // Now $b is array(0 => 'one', 1 =>'three') ?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array. Array do's and don'ts

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts: 

The above example is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Note: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them. 

More examples to demonstrate this behaviour:  'apple', 'veggie' => 'carrot'); // Correct print $arr['fruit']; // apple print $arr['veggie']; // carrot // Incorrect. This works but also throws a PHP error of level E_NOTICE because // of an undefined constant named fruit // // Notice: Use of undefined constant fruit - assumed 'fruit' in... print $arr[fruit];   // apple // This defines a constant to demonstrate what's going on. The value 'veggie' // is assigned to a constant named fruit. define('fruit', 'veggie'); // Notice the difference now print $arr['fruit']; // apple print $arr[fruit];   // carrot // The following is okay, as it's inside a string. Constants are not looked for // within strings, so no E_NOTICE occurs here print "Hello $arr[fruit]";     // Hello apple // With one exception: braces surrounding arrays within strings allows constants // to be interpreted print "Hello {$arr[fruit]}";   // Hello carrot print "Hello {$arr['fruit']}"; // Hello apple // This will not work, and will result in a parse error, such as: // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // This of course applies to using superglobals in strings as well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; // Concatenation is another option print "Hello ". $arr['fruit']; // Hello apple ?>

When error_reporting is set to show E_NOTICE level errors (for example by setting it to E_ALL), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works: 

This is an example of using a function return value as the array index. PHP also knows about constants: 

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing: 

Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why.

Converting to array:

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour: 

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing:

It is possible to compare arrays with the array_diff function and with array operators. Examples

The array type in PHP is very versatile. See examples below:  'red',           'taste' => 'sweet',            'shape' => 'round',            'name'  => 'apple',            4        // key will be 0          );

$b = array('a', 'b', 'c');

// . . .the above is completely equivalent with this: $a = array; $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[]       = 4;        // key will be 0 $b = array; $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // After the above code is executed, $a will be the array // array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', // 'name' => 'apple', 0 => 4), and $b will be the array // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c'). ?>

Example Using array:  4,              'OS'         => 'Linux',              'lang'       => 'english',              'short_tags' => true            ); // strictly numerical keys $array = array( 7,               8,                0,                156,                -10              ); // this is the same as array(0 => 7, 1 => 8, ...) $switching = array(        10, // key = 0                    5    =>  6,                    3    =>  7,                     'a'  =>  4,                            11, // key = 6 (maximum of integer-indices was 5)                    '8'  =>  2, // key = 8 (integer!)                    '02' => 77, // key = '02'                    0    => 12  // the value 10 will be overwritten by 12                  ); // empty array $empty = array; ?>

Example Collection: 

Changing the values of the array directly is possible since PHP by passing them by reference. Before that, a workaround is necessary:

Example Changing element in the loop: <?php // PHP 5 foreach ($colors as &$color) { $color = strtoupper($color); } unset($color); /* ensure that following writes to $color will not modify the last array element */ // Workaround for older versions foreach ($colors as $key => $color) { $colors[$key] = strtoupper($color); }

Example One-based index: <?php $firstquarter = array(1 => 'January', 'February', 'March'); print_r($firstquarter); ?>

Example Filling an array: <?php // fill an array with all items from a directory $handle = opendir('.'); while (false !== ($file = readdir($handle))) { $files[] = $file; } closedir($handle); ?>

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count function can be used to count the number of items in an array.

Example Sorting an array <?php sort($files); print_r($files); ?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Example Recursive and multi-dimensional arrays <?php $fruits = array ( "fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple" ),                 "numbers" => array ( 1, 2,                                      3,                                       4,                                       5,                                       6                                     ),                  "holes"   => array (      "first", 5 => "second", "third" )               );

// Some examples to address values in the array above echo $fruits["holes"][5];   // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference. <?php $arr1 = array(2, 3); $arr2 = $arr1; $arr2[] = 4; // $arr2 is changed, // $arr1 is still array(2, 3) $arr3 = &$arr1; $arr3[] = 4; // now $arr1 and $arr3 are the same ?>