AppDividend
Latest Code Tutorials

PHP array_combine Example | array_combine() Function Tutorial

0

PHP array_combine Example | array_combine() Function Tutorial is today’s topic. It creates an array by using the elements from one “keys” array and one “values” array. The array_combine() is the inbuilt function in PHP and is used to combine two arrays and create the new array by using one array for keys and another for values. 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.

PHP array_combine Example

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

array_combine(keys,values);

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);

The output is following.

 

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 represents 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);

The output is following.

 

PHP array_combine Example

Finally, PHP array_combine Example | array_combine() Function Tutorial is over.

Leave A Reply

Your email address will not be published.

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