Keys, Values and Columns
Four array functions pull an array apart into its keys, its values, one column, or a rebuilt map. Each one hands back a new array and leaves the given array unchanged.
array_keys lists the keys
The prices array is associative, so its keys are words. array_keys lifts those words into a plain list.
<?php
$prices = ["pen" => 5, "book" => 12, "bag" => 20];
$keys = array_keys($prices);
print_r($keys);array_values re-indexes the values
The scores sit under name keys here. array_values drops those keys and numbers the values from 0.
<?php
$scores = ["ana" => 8, "ben" => 9, "cy" => 7];
$values = array_values($scores);
print_r($values);array_column lifts one field
Each row holds a name and a price. array_column takes the name field from every row and builds one list of names.
<?php
$rows = [
["name" => "Pen", "price" => 5],
["name" => "Book", "price" => 12],
["name" => "Bag", "price" => 20],
];
$names = array_column($rows, "name");
print_r($names);array_combine zips two arrays
The first array gives the keys and the second array gives the values. array_combine pairs them in order and builds one associative array.
<?php
$keys = ["pen", "book", "bag"];
$values = [5, 12, 20];
$prices = array_combine($keys, $values);
print_r($prices);Example
<?php
$items = ["Pen", "Book", "Bag"];
$costs = [5, 12, 20];
$prices = array_combine($items, $costs);
print_r($prices);
echo $prices["Book"] . "\n";
$names = array_keys($prices);
print_r($names);Key points
- array_keys hands back every key of an array in the order the keys appear.
- array_values hands back every value of an array under fresh number keys that start at 0.
- array_column lifts one named field out of every row of an array of rows.
- array_combine builds an associative array from a keys array and a values array of the same length.
- An associative array is an array whose keys are text instead of numbers.
- Each of the four functions builds a new array, so the array given to it stays as it was.
In this example, two parallel arrays hold the item names and their costs. array_combine pairs them into one price list keyed by name. The price of Book reads straight from that list and prints as 12. array_keys then lifts the names back out as a numbered list.
Note
array_keys keeps the order the keys appear in the array, and that order is the order the values were added.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does array_values hand back for an associative array?