<?php
/*
Article Content: How to Use PHP’s array_combine() Function to Merge Two Arrays into an Associative Array
*/
// The PHP 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"];
// Using array_combine() to merge them
$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
// )
// Notes:
// 1. Both arrays must have the same number of elements, otherwise array_combine() will return false.
// 2. Values in the key array should be unique, otherwise duplicate keys will overwrite previous values.
// 3. The value array can contain any type of data, including strings, numbers, or even objects.
// Practical use case:
// array_combine() is very useful for converting form data, database query results, or configuration lists into an associative array.
// For example, suppose we have two arrays holding database field names and 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>"
";
?>
Related Tags:
array_combine