Skip to content

PHP Tutorial Arrays

Keys, Values and Combining Arrays

Lesson 130 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Many array tasks are about keys and values: getting them, swapping them or combining two lists.

array_keys() and array_values()

index.php
PHP
<?php
$stock = ["pens" => 40, "books" => 12];

print_r(array_keys($stock));
print_r(array_values($stock));
Output
OUTPUT
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

index.php
PHP
<?php
$keys = ["name", "city"];
$values = ["Isha", "Kochi"];

print_r(array_combine($keys, $values));
Output
OUTPUT
Array
(
    [name] => Isha
    [city] => Kochi
)

Both arrays need the same number of items, otherwise PHP throws a ValueError.

array_flip(): swap keys and values

index.php
PHP
<?php
$codes = ["IN" => "India", "NP" => "Nepal"];

print_r(array_flip($codes));
Output
OUTPUT
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().

index.php
PHP
<?php
$allowed = ["jpg", "png", "gif"];
$lookup = array_flip($allowed);

var_dump(isset($lookup["png"]));
var_dump(isset($lookup["exe"]));
Output
OUTPUT
bool(true)
bool(false)

array_column(): one field from many rows

index.php
PHP
<?php
$users = [
    ["id" => 1, "name" => "Ana"],
    ["id" => 2, "name" => "Ben"],
];

print_r(array_column($users, "name", "id"));
Output
OUTPUT
Array
(
    [1] => Ana
    [2] => Ben
)

array_fill_keys() and array_fill()

index.php
PHP
<?php
print_r(array_fill_keys(["a", "b"], 0));
echo implode(",", array_fill(0, 3, "x"));
Output
OUTPUT
Array
(
    [a] => 0
    [b] => 0
)
x,x,x

First and last key

index.php
PHP
<?php
$data = ["x" => 1, "y" => 2, "z" => 3];

echo array_key_first($data) . " " . array_key_last($data);
Output
OUTPUT
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)].

lightbulb
Keys must be unique
When you flip or combine arrays, a repeated key keeps only the last value. Check your data if items seem to vanish.