PHP
Create Associative Arrays from Two Lists
Learn how to efficiently create a PHP associative array by combining one array for keys and another for values using array_combine, perfect for mapping data.
<?php
$keys = ['id', 'name', 'email'];
$values = [101, 'Alice Smith', '[email protected]'];
$userProfile = array_combine($keys, $values);
print_r($userProfile);
// Expected Output:
// Array
// (
// [id] => 101
// [name] => Alice Smith
// [email] => [email protected]
// )
?>
How it works: The `array_combine()` function in PHP creates a new associative array by taking two arrays as input: one for the keys and one for the corresponding values. This is incredibly useful when you have separate lists of identifiers and their associated data, allowing you to quickly construct a key-value mapping without manual iteration. Both input arrays must have the same number of elements for the function to succeed.