PHP

Create Associative Array from Two Separate Arrays

Learn how to efficiently combine two indexed arrays, one for keys and one for values, into a single associative array in PHP using `array_combine`.

$keys = ['id', 'name', 'email'];
$values = [101, 'Jane Doe', '[email protected]'];

$userInfo = array_combine($keys, $values);
print_r($userInfo);
// Output: Array ( [id] => 101 [name] => Jane Doe [email] => [email protected] )

$countries = ['US', 'CA', 'MX'];
$capitals = ['Washington D.C.', 'Ottawa', 'Mexico City'];
$countryCapitals = array_combine($countries, $capitals);
print_r($countryCapitals);
// Output: Array ( [US] => Washington D.C. [CA] => Ottawa [MX] => Mexico City )
How it works: The `array_combine` function is a powerful tool for quickly creating an associative array when you have two separate indexed arrays: one containing the desired keys and the other containing the corresponding values. It's crucial that both input arrays have the same number of elements for the function to work correctly. This method is concise and highly readable for such transformations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs