November 26, 2022 | Posted in PHP
The array_combine() is a PHP built-in function that combines two arrays. It combines the keys of one array with the values of another array.
array_combine($keys_array, $values_array)
This array_combine() function accepts two parameters, and both are mandatory. The function gets the key(s) from the first parameter(array) and gets the values from the second parameter(array). Then combine them and return a new array.
Keep in mind the length of both arrays must be the same otherwise, PHP will through a fatal error.
Example: Let’s say we have an array that contains all the user IDs and another array that contains the user name. We want to combine these arrays to make another associative array.
<?php
$ids = [
100,
200,
300,
400
];
$name = [
'Md Khan',
'jhon Smith',
'Bob Wilson',
'Rani Sing'
];
$name_email = array_combine($ids,$name);
print_r($name_email);
#Output:
Array
(
[100] => Md Khan
[200] => jhon Smith
[300] => Bob Wilson
[400] => Rani Sing
)