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
$keys
and the values come from$values
. - Returns
false
if: $keys
and$values
do not have the same number of elements.- Either
$keys
or$values
is 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
$keys
contains duplicate values, only the last key-value pair will be retained in the result, as array keys must be unique. - Both
$keys
and$values
must 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.