js

Thursday, January 11, 2024

Explain array_combine() function in php

The array_combine() function in PHP is used to create an array by using one array for keys and another array for its corresponding values. It takes two arrays as input: one for keys and the other for values. The two arrays should have the same number of elements; otherwise, a warning will be issued.

Here is the syntax of array_combine():

php
array_combine(array $keys, array $values): array|false
  • $keys: An array containing keys.
  • $values: An array containing values.

The function returns an associative array where the values from the $keys array are used as keys, and the values from the $values array are used as corresponding values. If the input arrays have different lengths, array_combine() returns false.

Here's an example:

php
$keys = ['name', 'age', 'country']; $values = ['John', 25, 'USA']; $result = array_combine($keys, $values); print_r($result);

Output:

php
Array ( [name] => John [age] => 25 [country] => USA )

In this example, the elements in the $keys array become the keys, and the elements in the $values array become the corresponding values in the resulting associative array.

It's important to note that the arrays used as keys and values are not modified by array_combine(). If the input arrays have different lengths, array_combine() returns false, and it does not issue a warning. It's a good practice to ensure that the input arrays have the same length before using array_combine().

No comments:

Post a Comment