The array_combine() function in PHP allows you to create an associative array by using one array for keys and another for values. It is available in all PHP versions, including PHP 8.4, and there haven't been any changes to this function specific to PHP 8.4.
Syntax
array_combine(array $keys, array $values): array|false
Parameters
$keys: An array of keys to use for the new associative array.$values: An array of values to associate with the keys.
Return Value
- Returns the combined associative array where the keys come from
$keysand the values come from$values. - Returns
falseif: $keysand$valuesdo not have the same number of elements.- Either
$keysor$valuesis empty.
Example
// Two separate arrays for keys and values
$keys = ['name', 'age', 'city'];
$values = ['John', 30, 'New York'];
// Combine arrays into an associative array
$result = array_combine($keys, $values);
print_r($result);
Output:
Array
(
[name] => John
[age] => 30
[city] => New York
)
Notes
- If
$keyscontains duplicate values, only the last key-value pair will be retained in the result, as array keys must be unique. - Both
$keysand$valuesmust be numerically indexed arrays of equal length; otherwise, the function returnsfalse.
Error Handling Example
<?php
$keys = ['name', 'age'];
$values = ['John']; // Fewer values than keys
$result = array_combine($keys, $values);
if ($result === false) {
echo "Error: The number of keys and values must be the same!";
}
?>
PHP 8.4 Context
As of PHP 8.4, the array_combine() function behavior and usage remain unchanged. You can rely on its consistent functionality.