array_combine() Function Use in PHP

The PHP array_combine() function creates a new array by using one array’s values as keys and another array’s values as corresponding values.

Version Support: array_combine() in PHP 8.5, array_combine() in PHP 8.4, array_combine() in PHP 8.3, array_combine() in PHP 8.2, array_combine() in PHP 8.1, array_combine() in PHP 7.1, array_combine() in PHP 7.2, array_combine() in PHP 7.3, array_combine() in PHP 7.4

Syntax

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

  • $keys: Array whose values become the new array’s keys.
  • $values: Array whose values become the new array’s values.

Both arrays must have the same number of elements. Otherwise, PHP 8.0 and later throw a ValueError.

Example

<?php 

$keys = ["name", "age", "city"];

$values = ["Maya", 28, "Toronto"];

$result = array_combine($keys, $values);

print_r($result);

?>

Output:

Array

(    

[name] => Maya    

[age] => 28    

[city] => Toronto

)

Duplicate Keys

If the keys array contains duplicates, the later value overwrites the earlier one:

<?php 

$keys = ["color", "color"];

$values = ["red", "blue"];

$result = array_combine($keys, $values);

print_r($result);

?>

Output:

Array

(    

[color] => blue

)

Use array_combine() when you have two aligned lists—such as field names and form inputs and want to turn them into one associative array.


 

11 Views