PHP array_combine: How to Combine Array Based on Key/Values

The array_combine() is used to combine two arrays and create the new array by using one array for keys and another for values.

PHP array_combine()

PHP array_combine() is an inbuilt function that creates an array by using the elements from one “keys” array and one “values” array. 

That is all elements of one array will be the keys of the new array and all elements of the second array will be the values of the new array.

If we want to work with PHP array_combine() function, then both arrays must have an equal number of elements.

Syntax

The syntax of the array_combine() function is the following.

array_combine(keys,values);

Parameters

The keys parameter is required, and it is an array of keys.

The values parameter is required, and it is an array of values.

Let’s see an example. Write the following code inside the app.php file.

<?php

// app.php

$superHeros = ['Ironman', 'Thor', 'Captain America'];
$characterNames = ['Tony Stark', 'Thor', 'Steve Rogers'];
$finalArray = array_combine($superHeros, $characterNames);
print_r($finalArray);

See the output.

PHP array_combine Example | array_combine() Function Tutorial

The array_combine() function returns a new combined array, in which the elements from the first array $keys_array represents keys in the new array and elements from the second array $values_array represent the corresponding values in a new array.

The function returns the false if the number of elements in the two arrays is not the same.

The total number of elements in both of the arrays must be equal for the function to execute successfully. Otherwise, it will throw an error.

If two keys are the same, then the second one prevails. Let’s take a scenario where we take the same keys and see the following example.

<?php

// app.php

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

See the output.

PHP array_combine Example

Finally, PHP array_combine() example is over.

Leave a Comment

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