PHP

Creating an Associative PHP Array from Two Indexed Arrays

Combine two separate indexed PHP arrays, one containing keys and the other containing values, into a single associative array. Ideal for mapping related data.

<?php
// Define an array of keys
$countryCodes = ['US', 'CA', 'GB', 'DE', 'FR'];

// Define an array of corresponding values
$countryNames = ['United States', 'Canada', 'United Kingdom', 'Germany', 'France'];

// Use array_combine to create an associative array
$countryMap = array_combine($countryCodes, $countryNames);

print_r($countryMap);
/* Output:
Array
(
    [US] => United States
    [CA] => Canada
    [GB] => United Kingdom
    [DE] => Germany
    [FR] => France
)
*/

// Example with different lengths (array_combine will only use the shortest length)
$shortKeys = ['A', 'B'];
$longValues = ['Apple', 'Banana', 'Cherry'];
$combinedShort = array_combine($shortKeys, $longValues);

echo "
Combined with unequal lengths (keys shorter):
";
print_r($combinedShort);
/* Output:
Array
(
    [A] => Apple
    [B] => Banana
)
*/

$longKeys = ['X', 'Y', 'Z'];
$shortValues = ['Xylophone', 'Yacht'];
$combinedLong = array_combine($longKeys, $shortValues);

echo "
Combined with unequal lengths (values shorter):
";
print_r($combinedLong);
/* Output:
Array
(
    [X] => Xylophone
    [Y] => Yacht
)
*/
?>
How it works: The `array_combine()` function in PHP is a highly convenient way to create an associative array from two existing indexed arrays. It takes the first array's elements as keys and the second array's elements as their corresponding values. This is incredibly useful for scenarios like mapping country codes to full country names, product IDs to product names, or any situation where you have a one-to-one correspondence between two lists. It automatically handles cases where the input arrays have different lengths by using the length of the shorter array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs