Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_combine

Creates an array from two lists: keys and values.

Syntax

array_combine(array $keys, array $values): array

Parameters

ParameterTypeDescription
$keysarrayThe list of keys.
$valuesarrayThe list of values.

Return value

arrayAn associative array.

Examples

Headings and a table row:

<?php
 
$row = array_combine(['name', 'age'], ['Anna', 25]);
 
echo json_encode($row);

Output:

{"name":"Anna","age":25}

Values as their own keys:

<?php
 
$sizes = ['s', 'm', 'l'];
 
echo json_encode(array_combine($sizes, $sizes));

Output:

{"s":"s","m":"m","l":"l"}

Notes

If the lists differ in length, the function throws a ValueError.

See also

  • array_keys — Returns all the keys of an array.
  • array_values — Returns the values of an array with keys numbered from zero.
  • array_flip — Swaps keys and values.

Related recipes

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.