Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.
The `array_combine()` function in PHP combines two arrays by using one array for keys and another for its values. Here’s a usage example with PHP.
Syntax
<?php array_combine(array $keys, array $values): array|false ?>
1. $keys: An array of keys.
2. $values: An array of values.
Example
Here’s an example to demonstrate the use of `array_combine()`:
<?php $keys = ["name", "age", "email"]; $values = ["John Doe", 30, "john.doe@example.com"]; $combinedArray = array_combine($keys, $values); if ($combinedArray === false) { echo "The number of elements in the keys and values arrays do not match."; } else { print_r($combinedArray); } ?>
Explanation
1. Arrays to Combine:
– `$keys` contains the keys for the new array.
– `$values` contains the values for the new array.
2. Combining the Arrays:
– `array_combine($keys, $values)` creates a new array where each key from `$keys` is associated with the corresponding value from `$values`.
3. Checking for Errors:
– If the number of elements in `$keys` and `$values` are not the same, `array_combine()` returns `false`.
4. Output:
– If the arrays are combined successfully, it prints the combined array.
Output
<?php Array ( [name] => John Doe [age] => 30 [email] => john.doe@example.com ) ?>
In this example, `array_combine()` successfully combines the keys and values into a single associative array. If the number of keys and values did not match, it would return `false`.