PHP array_combine function

PHP array_column function
PHP array_count_values() function

In PHP, the array_combine() method is used to generate an array by combining two arrays, one as keys and the other as values. The function will return a false value if the number of elements in both arrays is not equal.

The array_combine() method has the following syntax:

What is the syntax of the array_combine function in PHP?

array array_combine ( array $keys , array $values )
ParameterDescription
keysAn array of keys – required
valuesAn array of values – required
array_combine function in PHP

The array that will be used as keys is specified by the $keys argument, while the array that will be used as values is specified by the $values parameter.

Let’s look at a few samples to see how the array_combine() method works:

$keys = array("red", "green", "blue");
$values = array("apple", "banana", "cherry");
$fruits = array_combine($keys, $values);
print_r($fruits);

Output:

Array
(
    [red] => apple
    [green] => banana
    [blue] => cherry
)

The $keys array is utilized as the keys in this example, while the $values array is used as the values, resulting in a new associative array $fruits.

Exampe 2.

$keys = array("red", "green", "blue");
$values = array("apple", "banana");
$fruits = array_combine($keys, $values);
print_r($fruits);

Output:

bool(false)

In this example, the number of elements in the $keys and $values arrays are not equal, so the function returns a false value.

Example 3:

$keys = array(1, 2, 3);
$values = array("apple", "banana", "cherry");
$fruits = array_combine($keys, $values);
print_r($fruits);

Output:

Array
(
    [1] => apple
    [2] => banana
    [3] => cherry
)

The $keys array in this example employs numerical values as keys, resulting in a numerical associative array.

Finally, the array_combine() method in PHP is a valuable tool for merging two arrays to create an associative array. It is critical to notice that the number of entries in both arrays must be equal else the function would return a false value.

PHP array_column function
PHP array_count_values() function
en English
X
Scroll to Top