← Back to all snippets
PHP

Combine Two Arrays into Key-Value Pairs

Learn to create an associative array by using elements from one array as keys and elements from another as their corresponding values with `array_combine()`.

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

$person = array_combine($keys, $values);
print_r($person);
// Expected Output: Array ( [name] => John Doe [age] => 30 [city] => New York )

$productIds = [101, 102, 103];
$productNames = ['Laptop', 'Mouse', 'Keyboard'];
$products = array_combine($productIds, $productNames);
print_r($products);
// Expected Output: Array ( [101] => Laptop [102] => Mouse [103] => Keyboard )
?>
How it works: The `array_combine()` function creates an associative array by using the values from one array as keys and the values from another array as their corresponding values. Both input arrays must have the same number of elements, otherwise, a warning will be generated. This is perfect for when you have separate lists of identifiers and their corresponding data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs