array_combine() Function Use In PHP 7.1 With Example

The `array_combine()` function in PHP is used to create an array by combining two arrays—one for keys and one for values. This function is available in PHP 5 and later, including PHP 7.1.

Syntax

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

$keys: The array of keys.
$values: The array of values.

Rules

1. The number of elements in the `$keys` and `$values` arrays must be the same. If they are not, the function will return `FALSE`.
2. If either array is empty, the function will return `FALSE`.

Example

Here is an example of how to use `array_combine()`:

<?php
$keys = ["name", "age", "gender"];
$values = ["John", 25, "male"];
$combinedArray = array_combine($keys, $values);
if ($combinedArray === FALSE) {
echo "The keys and values arrays must have the same number of elements.";
} else {
print_r($combinedArray);
}
?>

Output

<?php
Array
(
[name] => John
[age] => 25
[gender] => male
)
?>

In this example:

1. The `$keys` array contains the keys `name`, `age`, and `gender`.
2. The `$values` array contains the corresponding values `John`, `25`, and `male`.
3. The `array_combine()` function combines these two arrays into a single associative array.

Error Handling

If the two arrays do not have the same number of elements, or if either array is empty, the function will return `FALSE`.

Example:

<?php
$keys = ["name", "age"];
$values = ["John"];
$combinedArray = array_combine($keys, $values);
if ($combinedArray === FALSE) {
echo "The keys and values arrays must have the same number of elements.";
}
?>

Output:

<?php
The keys and values arrays must have the same number of elements.
?>

This output occurs because the number of elements in the `$keys` array does not match the number of elements in the `$values` array.