array_combine() Function Use In PHP 7.2 With Example

The `array_combine()` function in PHP combines two arrays by using one array as keys and the other as values. It requires both arrays to have the same number of elements. If they don’t, the function will return `false`.

Syntax

<?php
array_combine(array $keys, array $values): array|false
?>

$keys: An array of keys.
$values: An array of values.

Example

<?php
$keys = ["apple", "banana", "cherry"];
$values = [1.2, 0.5, 2.3];
$result = array_combine($keys, $values);
if ($result === false) {
echo "The arrays do not have the same number of elements.";
} else {
print_r($result);
}
?>

Output

<?php
Array
(
[apple] => 1.2
[banana] => 0.5
[cherry] => 2.3
)
?>

Explanation

– The `array_combine()` function creates an associative array where each element of the first array (`$keys`) becomes a key, and the corresponding element from the second array (`$values`) becomes the value.
– If the arrays have a different number of elements, the function returns `false`.