Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP array_combine function

Creates a new array by combining two given arrays, where the values of the first array become the keys of the new array, and the values of the second array become the values of this new array.

Description / Descripción
array_combine(array $keys, array $values): array
Sintaxis / Sintax
$new_array = array_combine($array1,$array2);

If you’d like to visualize it more clearly, we can refer back to the image we saw in the PHP array functions.

PHP combine_array

if we have the following arrays:

Array 1Array2
[0] => a
[1] => b
[2] => c
[3] => d
[0] => 1
[1] => 2
[2] => 3
[3] => 4

Our new array will be:

New Array
a => 1
b => 2
c => 3
d => 4

Parameters

$keys array from which I will obtain the keys.

$values array from which I will obtain the values.

Return

New array using the values from the $keys array as keys and the values from the $values array as values.

Ejemplo

In this example, we will use the values from the image in case it’s still not clear.

$array1 = ["a","b","c","d"];
$array2 = [1,2,3,4];
$nuevo_array = array_combine($array1,$array2);
var_dump($nuevo_array);
array(4) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
  ["d"]=>
  int(4)
}

Does it create only an associative array? Not necessarily; let’s take a look at the following example.


array(4) {
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
}

Warning: Undefined array key 0 in /home/user/scripts/code.php on line 6

As you can see here, we have a regular indexed array. We just need to be careful when referencing a position with a value. In this case, when referencing $new_array[0], it has given us a warning.

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category