PHP

Combine Two Arrays into an Associative Array

Learn how to merge two separate PHP arrays, one for keys and one for values, into a single associative array using the array_combine() function. Essential for structured data.

<?php
$keys = ['name', 'age', 'city'];
$values = ['Alice', 30, 'New York'];

// Combine them into an associative array
$person_data = array_combine($keys, $values);
print_r($person_data);

// Example with different lengths (will return false)
$short_keys = ['item', 'price'];
$long_values = ['Laptop', 1200, 'Electronics'];
$invalid_combination = array_combine($short_keys, $long_values);
var_dump($invalid_combination);
?>
How it works: The `array_combine()` function is used to create an associative array by taking two arrays: one for the keys and one for the values. Both input arrays must have the same number of elements; otherwise, the function will return `false`. This snippet is highly useful when you have data separated into two lists and need to construct a mapping or a structured record from them.

Need help integrating this into your project?

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

Hire DigitalCodeLabs