PHP Array
Use PHP Array as a key & value map
# PHP array contains elements of key/value pair
$a = array('text' => 'string', 10 => 4, 'absent' => TRUE);
echo $a['text']; # 'string'
echo $a[10]; # 4
echo $a['absent']; # 1
echo "$a[text]"; # If the variable is inside double quote "", text does NOT need to be quoted
Accessing PHP Array using index
$a = array('text' => 'string');
echo $a['text']; # 'string'
define('text', 'constant');
echo $a[text]; # A common mistake: not the same as $a['text']
# text here refer to the global constant (text)
PHP array key
- Can either be a string or an integer
- Other numeric type will truncate to an integer
Removing (unset) PHP array elements
unset($a[4]); # Delete an element of an array
unset($a); # Delete $a
Use PHP Array as a 1-dimensional array
$a1 = array(2, 1, 0); # Without a key, key value starts from 0 and increment by 1 each time
# array(3) { [0]=> int(2) [1]=> int(1) [2]=> int(0) }
# An array of length 3 with key 0, 1 & 2
Append an element to the end of a PHP array
$a1[] = 4; # Append an element: array(0=>2, 1=>1, 2=>0, 3=>4)
Create an empty PHP array
$a1 = array(); # Empty array
Start a PHP array with a specific key value
$months = array(1=>'Jan', 'Feb', 'Mar', 'Apr'); # Key starts from 1
$a2[3] = 9; # array(1) { [3]=> int(9) }
Create a PHP array with a range of value
$a = range(0, 5); # array(0, 1, 2, 3, 4, 5);
$a = range('a', 'z');
Multi-dimensional PHP Array
$a = array("item" => array("text" => "string", 10 => 4, "absent" => TRUE) , 'flag' => TRUE);
echo $a['item']['text']; # 'string'
echo $a['item'][10]; # 4
echo $a['item']['absent']; # 1
PHP Array indexing
When a key is missing ($a[] = 'text'; ), PHP uses the next available integer index
- Find the maximum integer index (n) used in the array
- Use n+1 as the next index
$a = array(1 => '0', 3 => 'a', 'b', 'c', 'flag' => 'b', 20 => 'y', 'z');
echo $a[3]; # 'a'
echo $a[4]; # 'b'
echo $a[5]; # 'c'
echo $a[21]; # 'z'
$a[] = 'd'; # Same as $a[22] = 'd' which 22 is the next index value for $a
$a['option'] = 'e';
PHP Array Key & Value Functions
Return all keys in a PHP array
$a = array(3 => 'a', 'b', 'c');
$k = array_keys($a);
Re-index the array with key starts from 0
Check the presence of a key or a value in a PHP array
Find if a key exists in a PHP array
$b = array_key_exists('key_name', $a); # TRUE if key exists
$b = isset($a['key_name']); # TRUE if key exists and the value is not NULL
Find if a specific element exists in a PHP array
$a = array('x', 'y', 'z');
$b = in_array('x', $a); # TRUE: 'x' is in $a
Find the key by the PHP array element value
$k = array_search('x', $a); # Return the key for value 'x'
PHP Array Copy, Replace, Insert & Delete
PHP array assignment (PHP array assignment is copy by value)
$a = array('a', 'b', 'c');
$a2 = $a;
- A duplicate copy of the array (copy by value) is made
- Change in one array have no impact on other
$a = array("original");
$b = $a;
$a[0] = "new"; // $b[0] will remain as "original"
To copy PHP array by reference
$a3 = &$a; # A variable alias. Changes impact both $a and $a3
Return a sub-set of a PHP array
$r = array_slice($a, 1, 2); # Return an array starting at index 1 with max of 2 elements
# array(2) { [0]=> string(1) "b" [1]=> string(1) "c" }
Merge PHP array elements into sub-array of size 2
$r = array_chunk($a, 2); # Merge array elements into sub-array elements of size 2
# array(2) { [0]=> array(2) { [0]=> string(1) "a" [1]=> string(1) "b"}
# [1]=> array(1) { [0]=> string(1) "c" } }
#
Remove PHP array elements
$r = array_splice($a, 2, 3); # Remove max of 3 elements starting at index 2 from $a (in-place)
# The removed elements are stored in $r
# $a: array(2) { [0]=> string(1) "a" [1]=> string(1) "b"}
# $r: array(1) { [0]=> string(1) "c"}
$r = array_splice($a, 2); # Remove elements of $a starting at index 2 to the end
$r = array_splice($a, 1, 2, array(4, 5)); # Remove and then insert an array
Pad a PHP array
$r = array_pad($a, 5, 0); # Pad the array with 0 to a max of 5 elements
PHP Array Function
Assign array's element to different variables
$a = array(1, 2, 3);
list($v1, $v2, $v3, $v4) = $a; # Assign $v1=$a[0]; $v2=$a[1]; $v3=$a[2]; $v4=NULL;
Un-pack the returned function's array result to a list of PHP variables
list($v1, $v2, $v3, $v4) = some_func(); # some_func() can return an array like return array(1, 3);
Merge 2 PHP arrays
$r = array_merge($a1, $a2); # Merge 2 array with $a1 elements come first
# If an element in $a2 has the same key as $a1, $a2 value will be used
PHP Array difference
$a1 = array(1,2);
$a2 = array(2,3);
$r = array_diff($a1, $a2); # Return an array containing the difference
# array(1) { [0]=> int(1) }
Count the number of elements in a PHP array
$t = count($a); # Number of count
Sum all the elements of a PHP array
$total = array_sum($a); # Sum of array elements
print_r($a1); # Print the array
Reverse, Flip or Shuffle PHP array elements
$r = array_reverse($a); # Reverse an array
$r = array_flip($a); # Flip the key with value
shuffle($a); # Randomized the order of the elements
Use function call back to filter out PHP array elements
function is_even ($v) {
if (($v%2)==0) {
return TRUE;
}
return FALSE;
}
$a = array(1, 6, 2, 4);
$r = array_filter($a, 'is_even'); # Create another array from $a that has even number only
Create variables from array (or vice versa)
$a = array("v1" => 1, "v2" => 2); # Create variables from array
extract($a, EXTR_PREFIX_ALL, "value"); # Same as $value_v1=1; $value_v2 = 2;
$v1 = 1;
$v2 = 2; # Opposite of extract
$a = compact('v1', 'v2'); # array(2) { ["v1"]=> int(1) ["v2"]=> int(2) }
PHP array operation
| PHP Array Operation |
Description |
| $a1 + $a2 |
Union |
| $a1 == $a2 |
Equal if both array have the same key/value pairs |
| $a1 === $a2 |
Equal if both have the same key/value pairs in the same order and of types |
| != <> |
Not == |
| $a !== $b |
Not === |
PHP Array Iteration
Iterate through a PHP array
$months = array(1=>'Jan', 'Feb', 'Mar', 'Apr');
foreach ($months as $month) {
echo "$month";
}
Iterate through a PHP array with key & value pair
foreach ($months as $key => $month) {
echo "$key $month";
}
Iterate through a PHP array with key & value pair by reference
foreach ($months as &$month) { # Pass by reference
$month = strtoupper($month); # so in-place assignment is possible
}
without the reference, making change to "$month" will have no impact on the $months array
PHP iterate function
# Reset the iterator to the beginning
reset($a);
# Iterate each key/value in the array
while (list($key, $value) = each($a)) {
echo $key, $value;
}
| PHP Array Iteration Function |
Description |
| current( ) |
Current iterator element |
| reset( ) |
Move back to first element |
| next( ) |
Move to next element and return it |
| prev( ) |
Move back and return it |
| end( ) |
Move to last element and return it |
| each( ) |
return current key/value as an array and move to next element |
| key( ) |
key of current element |
PHP array_walk: Calling a function in visiting every element of a PHP array
function visit($value, $key) {
...
}
function visit2($value, $key, $p1) {
...
}
$a = array(1, 2, 3);
array_walk($a, 'visit');
array_walk($a, 'visit2', 'some parameter');
PHP Array Aggregate features
function sum ($total, $value) {
$total += $value;
return $total;
}
$a = array(1, 2, 3);
$sum = array_reduce($a, 'sum'); # 6
$sum = array_reduce($a, 'sum', 4); # 10: Start $total with 4
PHP Array Sorting Functions
| PHP Array Function |
Sorts by |
Maintain key/value association |
Sorting order |
| array_multisort() |
value |
Not on numeric key |
first array |
| asort() |
value |
yes |
ASC |
| arsort() |
value |
yes |
DESC |
| krsort() |
key |
yes |
DESC |
| ksort() |
key |
yes |
ASC |
| natcasesort() |
value |
yes |
Natural & case insensitive |
| natsort() |
value |
yes |
Natural |
| rsort() |
value |
no (key restart from 0) |
DESC |
| shuffle() |
value |
no (key restart from 0) |
Random |
| sort() |
value |
no (key restart from 0) |
ASC |
| uasort() |
value |
yes |
User defined |
| uksort() |
key |
yes |
User defined |
| usort() |
value |
no (key restart from 0) |
User defined |
PHP user define comparator
function custom_sort($a, $b) {
if ($a == $b) {
return 0;
}
return (($a < $b) ? -1 : 1);
}
$a = array (1, 4, 4, 2, 7);
uasort($a, 'custom_sort');
Sort array that contain value with both numeric and string (like 'time3', 'time10')
natsort($a);
natcasesort($a);
Sort by $a1, then $a2 and last $a3
array_multisort($a1, SORT_ASC, $a2, SORT_DESC, $a3, SORT_DESC);
PHP Array Functions (Quick Reference)
| Functions |
Description |
| array_change_key_case |
Change the case of the keys |
| array_chunk |
Split an array into chunks |
| array_combine |
Create an array using one array as keys and another for values |
| array_count_values |
Count the number of occurrence for unique key |
| array_diff_assoc |
Find the difference. Comparing key/value |
| array_diff_key |
Find the difference. Only comparing key |
| array_diff_uassoc |
Find the difference with user defined comparator on indexes |
| array_diff_ukey |
Find the difference with user defined comparator on keys |
| array_diff |
Difference on an array |
| array_fill_keys |
Fill an array with value/key |
| array_fill |
Fill an array with values |
| array_filter |
Filters elements of an array with a callback function |
| array_flip |
Flip key/value |
| array_intersect_assoc |
Intersection of arrays with index check |
| array_intersect_key |
Intersection of arrays using keys for comparison |
| array_intersect_uassoc |
Intersection of arrays with index check with a callback function |
| array_intersect_ukey |
Intersection of arrays using a callback function on the keys |
| array_intersect |
Intersection of arrays |
| array_key_exists |
Key exists in an array |
| array_keys |
Return an array of all keys |
| array_map |
Call the callback for all elements in an array |
| 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 |
| array_pop |
Pop the element from an array |
| array_product |
Product of values in an array |
| array_push |
Push an array |
| array_rand |
Pick an element randomly |
| array_reduce |
Aggregate the array to a single value using a callback function |
| array_replace_recursive |
Replaces elements of first array by another array recursively |
| array_replace |
Replaces elements of first array by another array |
| array_reverse |
Reverse an array |
| array_search |
Search for a given value and return the key |
| array_shift |
Shift an element off from the beginning |
| array_slice |
Slice an array |
| array_splice |
Slice an array and replace it with other elements |
| array_sum |
Sum of an array |
| array_udiff_assoc |
The difference of arrays with index check & compares value with a callback function |
| array_udiff_uassoc |
The difference of arrays with index check, compares key/value with a callback function |
| array_udiff |
The difference of arrays comparing value with a callback function |
| array_uintersect_assoc |
Intersection of arrays with index check, compares value with a callback function |
| array_uintersect_uassoc |
The intersection of arrays with index check, compares key/values with a callback functions |
| array_uintersect |
The intersection of arrays, compares value with a callback function |
| array_unique |
Removes duplicate values |
| array_unshift |
Prepend elements to the beginning of an array |
| array_values |
Values of an array |
| array_walk_recursive |
Call a user function for each element of an array recursively |
| array_walk |
Call a user function for each element of an array |
| array |
Create an array |
| compact |
Create array with variables/values |
| count |
Count elements in an array |
| extract |
Import variables from an array |
| in_array |
Value exists in an array |
| list |
Assign variables from an array |
| range |
An array containing a range of values |
| shuffle |
Shuffle an array |
| sizeof |
Count of an array |
|