PHP
Create Associative Array from Separate Key and Value Lists
Discover how to quickly construct a new associative array by combining two separate arrays: one for keys and one for their corresponding values.
<?php
$keys = ['id', 'name', 'email'];
$values = [101, 'Alice', '[email protected]'];
$userProfile = array_combine($keys, $values);
print_r($userProfile);
// Example with mismatched counts (will return false and trigger a warning)
$shortKeys = ['id', 'name'];
$longValues = [202, 'Bob', '[email protected]'];
$invalidCombine = array_combine($shortKeys, $longValues); // This will be false
if ($invalidCombine === false) {
echo "
Warning: array_combine failed due to mismatched key/value counts.
";
}
?>
How it works: The `array_combine()` function is used here to create an associative array. It takes two arrays as arguments: the first array provides the keys, and the second array provides the corresponding values. Both arrays must have an equal number of elements; otherwise, `array_combine()` will return `false`.