<?php
/*
Article: How to Use PHP’s array_combine() Function to Merge Two Arrays into an Associative Array?
*/
// PHP’s array_combine() function is used to merge two arrays into an associative array.
// The first array will serve as the keys of the new array, and the second array will serve as the values.
// Example: Suppose we have two arrays
$keys = ["name", "age", "city"];
$values = ["Alice", 25, "Beijing"];
// Merge using array_combine()
$combinedArray = array_combine($keys, $values);
// Output the result
echo ""</span></span><span>;<br>
</span><span><span class="function_ invoke__">print_r</span></span><span>(</span><span><span>$combinedArray</span></span><span>);<br>
</span><span><span>echo</span></span><span> </span><span><span>"
";
// The output will be:
// Array
// (
// [name] => Alice
// [age] => 25
// [city] => Beijing
// )
// Important notes:
// 1. Both arrays must have the same number of elements; otherwise, array_combine() will return false.
// 2. Values in the keys array should be unique; otherwise, duplicate keys will overwrite previous values.
// 3. The values array can contain any type of data, including strings, numbers, or even objects.
// Practical use cases:
// array_combine() is perfect for converting form data, database query results, or configuration lists into an associative array.
// For example, suppose we have two arrays storing database field names and their corresponding values:
$fields = ["username", "email", "password"];
$data = ["bob123", "[email protected]", "securepass"];
$user = array_combine($fields, $data);
echo ""</span></span><span>;<br>
</span><span><span class="function_ invoke__">print_r</span></span><span>(</span><span><span>$user</span></span><span>);<br>
</span><span><span>echo</span></span><span> </span><span><span>"
";
?>