- An array can be created as
array( key1 => value1, key2 => value2, key3 => value3, ... )
- As of PHP 5.4, we can use [] instead of array().
- The key can either be an integer or a string.
- In the keys, Floats, Bools and Strings containing valid decimal integers are cast to integers.
- Same keys overwrite previous ones.
$array = array( 1 => "a", "1" => "b", 1.5 => "c", true => "d", ); print_r($array); # Array ( [1] => d ) var_dump$array); # array(1) { [1]=> string(1) "d" }
- The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.
- To change a certain value, assign a new value to that element using its key (like list or dict in Python).
- To delete element from array use unset():
$arr = array(5 => 1, 12 => 2, 17 => 6); unset($arr[5]) # This removes the first element of array. unset($arr) # This deletes the whole array
- To reindex after deletting an entry, use array_values().
- The foreach control structure exists specifically for arrays and objects:
$arr = [1, 3, 5, 7]; foreach ($arr as $key => $value) { # If we don't need the key, we can write '$arr as $value' ... }
- Changing the values of an array directly is possible by passing them by reference :
$colors = ['red', 'blue', 'green', 'yellow']; foreach ($colors as &$color) { # '&' is used to pass by reference. $color = strtoupper($color); } unset($color); /* ensuring that following writes to $color will not modify the last array element. */
- Array assignment always involves value copying. Use assignment by reference to change both items involved:
$arr1 = [2, 3]; $arr2 = $arr1; $arr2[0] = 4; # $arr2 is changed to [4, 3], # $arr1 is still [2, 3] $arr3 = &$arr1; $arr3[0] = 4; // now $arr1 and $arr3 are the same