PHP array_combine() Function

PHP array_combine() function is “used to combine two arrays and create a new array by using one array for keys and another array for values.”

The number of elements in both arrays must be equal, as the function returns false if the number of elements does not match.

Syntax

array_combine(keys,values);

Parameters

  1. keys: It is required and an array of keys.
  2. values: It is required, and it is an array of values.

Return value

It returns a new combined array, in which the elements from the first array $keys_array represent keys in the new array, and the elements from the second array $values_array represent the corresponding values in the new array. 

Visual RepresentationVisual Representation of PHP array_combine() Function

Example 1: How to Use array_combine() function

<?php

$superHeros = ['Ironman', 'Thor', 'Captain America'];
$characterNames = ['Tony Stark', 'Thor', 'Steve Rogers'];

$finalArray = array_combine($superHeros, $characterNames);
print_r($finalArray);

Output

Array
(
 [Ironman] => Tony Stark
 [Thor] => Thor
 [Captain America] => Steve Rogers
)

In this example, three keys Ironman, Thor, and Captain America are combined with the values Tony Stark, Thor, and Steve Rogers. The resulting array $finalArray uses Ironman, Thor, and Captain America as keys for the respective values. 

Example 2: If two keys are the sameVisual Representation of If two keys are the same

<?php

$x = ['a', 'b', 'b', 'c'];
$y = ['A', 'B', 'K', 'C'];
$finalArray = array_combine($x, $y);
print_r($finalArray);

Output

Array
(
 [a] => A
 [b] => K
 [c] => C
)

In PHP, array keys must be unique. If there are duplicate keys in $a array (In the above example, ‘b’ appears twice), only the last key-value pair is used, with earlier occurrences being overwritten.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.