Many array tasks are about keys and values: getting them, swapping them or combining two lists.
array_keys() and array_values()
<?php
$stock = ["pens" => 40, "books" => 12];
print_r(array_keys($stock));
print_r(array_values($stock));
Array
(
[0] => pens
[1] => books
)
Array
(
[0] => 40
[1] => 12
)
array_values() is also the way to re-number an array after filtering or unset().
array_combine(): two lists become a record
<?php
$keys = ["name", "city"];
$values = ["Isha", "Kochi"];
print_r(array_combine($keys, $values));
Array
(
[name] => Isha
[city] => Kochi
)
Both arrays need the same number of items, otherwise PHP throws a ValueError.
array_flip(): swap keys and values
<?php
$codes = ["IN" => "India", "NP" => "Nepal"];
print_r(array_flip($codes));
Array
(
[India] => IN
[Nepal] => NP
)
array_flip() is handy to look up by value. Values must be strings or integers.
A fast “is it in the list?” check
Searching with in_array() checks every item. For a big list that you check many times, flip it once and use isset().
<?php
$allowed = ["jpg", "png", "gif"];
$lookup = array_flip($allowed);
var_dump(isset($lookup["png"]));
var_dump(isset($lookup["exe"]));
bool(true)
bool(false)
array_column(): one field from many rows
<?php
$users = [
["id" => 1, "name" => "Ana"],
["id" => 2, "name" => "Ben"],
];
print_r(array_column($users, "name", "id"));
Array
(
[1] => Ana
[2] => Ben
)
array_fill_keys() and array_fill()
<?php
print_r(array_fill_keys(["a", "b"], 0));
echo implode(",", array_fill(0, 3, "x"));
Array
(
[a] => 0
[b] => 0
)
x,x,x
First and last key
<?php
$data = ["x" => 1, "y" => 2, "z" => 3];
echo array_key_first($data) . " " . array_key_last($data);
x z
PHP 8.5 added array_first() and array_last() to read the first and last value directly. On older versions, use $data[array_key_first($data)].