In PHP, the array_combine() method is used to generate an sreath 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:
Dè an co-chòrdadh a th’ aig gnìomh array_combine ann am PHP?
array array_combine ( array $keys , array $values )
paramadair | Tuairisgeul |
---|---|
iuchraichean | Sreath de iuchraichean - a dhìth |
luachan | Sreath de luachan - a dhìth |
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);
Toraidhean:
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);
Toraidhean:
bool(false)
In this example, the number of elements in the $keys
agus $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);
Toraidhean:
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.