Home
PHP
array Examples (Dictionary Keys)
This page was last reviewed on Jun 2, 2023.
Dot Net Perls
Array. In PHP an array is a special type that can have keys and values. It is more like a dictionary in other languages, but can be used like a list as well.
Shows an arrayShows an array
We can append to an array by assigning to an empty key. And with unset() we can remove a key entirely. Creating an array can be done with a clear and concise statement.
Dictionary example. Here we use the array as a dictionary with string keys—each entry has a string as the key, and an int as the value.
Step 1 We create the array with fat arrows. Each string key has one int value—there are 3 entries total.
Step 2 We access a string key from the array. This performs a lookup and finds the value for "frog."
Step 3 We print the value we found from the array, which is 50. We can see the values are typed as ints.
Shows an array
// Step 1: create array as dictionary with string keys. $animals = array("bird" => 100, "frog" => 50, "cat" => 200); // Step 2: look up value of string key. $frog = $animals["frog"]; // Step 3: print value. var_dump($frog);
int(50)
Foreach key, value. Consider a PHP dictionary (an array with keys and values). We may want to loop over the keys and values and display or test them.
Here We use a foreach-loop with the fat-arrow syntax to access each key and value in the dictionary.
$colors = array("ochre" => 1, "mauve" => 50, "avocado" => 10); // Loop over keys and values with fat arrow in foreach. foreach ($colors as $key => $value) { echo "Key is " . $key . " and value is " . $value . "\n"; }
Key is ochre and value is 1 Key is mauve and value is 50 Key is avocado and value is 10
Remove element. How can we remove an element from a PHP array? This can be done with the unset() function, which receives the array and the index we want to remove.
Tip We call unset() with the key. If there are known keys, we use those, but if the keys are not specified, we use 0, 1, 2 and further.
Shows an array
$codes = [100, 200, 300]; // Remove the second (index 1) element. unset($codes[1]); var_dump($codes);
array(2) { [0]=> int(100) [2]=> int(300) }
Append. It is possible to append to the end of an array. The syntax shown here adds an element to the last index plus 1. The example appends each week day to the array.
// Create an empty array. $days = []; // Append each value to the end of the array. $days[] = "Monday"; $days[] = "Tuesday"; $days[] = "Wednesday"; var_dump($days);
array(3) { [0]=> string(6) "Monday" [1]=> string(7) "Tuesday" [2]=> string(9) "Wednesday" }
Foreach, reference. Iterating over the elements in an array is commonly done. We can use the foreach-loop with the "as" syntax to enumerate our array.
foreach
Tip By default, each array element cannot be changed in a foreach. But if we use the ampersand, we can mutate the original array elements.
$colors = array("red", "orange", "green"); // Use foreach loop over the color array. foreach ($colors as $color) { var_dump($color); } // Use foreach loop and modify each element. foreach ($colors as &$color) { $color = "blue"; } var_dump($colors);
string(3) "red" string(6) "orange" string(5) "green" array(3) { [0]=> string(4) "blue" [1]=> string(4) "blue" [2]=> &string(4) "blue" }
Combine arrays. Suppose we have 2 arrays and want to combine them into one array. This can be done with the built-in array_merge function.
$colors = ["blue", "red"]; $colors_rare = ["vermilion", "turquoise"]; // Append one array to another. $result = array_merge($colors, $colors_rare); var_dump($result);
array(4) { [0]=> string(4) "blue" [1]=> string(3) "red" [2]=> string(9) "vermilion" [3]=> string(9) "turquoise" }
Reverse. It is possible to reverse the ordering of elements in an array with array_reverse. This is different from sorting the array—no sorting is done.
$values = [0, 50]; // Reverse the array. $result = array_reverse($values); var_dump($result);
array(2) { [0]=> int(50) [1]=> int(0) }
Map. The "map" function for an array calls a function on each element and modifies the element with the result. In PHP we invoke array_map for this feature.
Argument 1 The first argument to array_map is the function that must be called on each element. We use a lambda here.
function
Argument 2 This is the array that we are acting upon. Note that we must assign a new array variable to the result of array_map.
$values = ["BIRD", "LIZARD"]; // Call function on each element to modify it. $mapped = array_map(fn($a) => strtolower($a) . "...", $values); var_dump($mapped);
array(2) { [0]=> string(7) "bird..." [1]=> string(9) "lizard..." }
In array. Does a specific element exist in an array? We could use a foreach-loop to try to find a matching element, but calling in_array is often simpler.
$sizes = [0, 1, 2]; // See if the value is in the array. if (in_array(2, $sizes)) { echo "2 in array\n"; } // This value is not in the array. if (!in_array(100, $sizes)) { echo "100 not in array\n"; }
2 in array 100 not in array
Array is a complex type in PHP—it serves both as a dictionary type and a list. This gives us the ability to use key-based lookups, and also easy appends and looping.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 2, 2023 (edit link).
Home
Changes
© 2007-2024 Sam Allen.