PHP

Combine Two Arrays into Associative Array

Master creating an associative array in PHP by combining two separate arrays: one providing the keys and another providing the values, perfect for dynamic mapping.

<?php
$columnNames = ['id', 'firstName', 'lastName', 'email'];
$userDataRow = [101, 'Jane', 'Doe', '[email protected]'];

// Combine them into an associative array
$userProfile = array_combine($columnNames, $userDataRow);

echo "Combined User Profile:
";
print_r($userProfile);

// Example with different lengths (will result in warning, values array truncated)
$shortColumnNames = ['id', 'name'];
$fullUserDataRow = [202, 'Peter', 'Jones', '[email protected]'];
$shortProfile = array_combine($shortColumnNames, $fullUserDataRow); // Values array will be truncated
echo "
Combined (mismatched length - values truncated):
";
print_r($shortProfile);

// Example with different lengths (will result in warning, keys array truncated)
$fullColumnNames = ['id', 'firstName', 'lastName', 'email', 'phone'];
$shortUserDataRow = [303, 'Alice', 'Smith'];
$fullProfile = array_combine($fullColumnNames, $shortUserDataRow); // Keys array will be truncated
echo "
Combined (mismatched length - keys truncated):
";
print_r($fullProfile);
?>
How it works: This snippet showcases `array_combine()`, a powerful PHP function used to create an associative array from two separate, equally-sized arrays. One array provides the keys, and the other provides the corresponding values. The example also illustrates the behavior when the input arrays have different lengths: the function will issue a warning and truncate the longer array to match the shorter one, preventing unexpected results.

Need help integrating this into your project?

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

Hire DigitalCodeLabs