How to insert the elements of the array X into an index of the array Y?

2

I have the array y where in its index 0 has the values App and Views

array (size=1)
  0 => 
    array (size=2)
      0 => string 'App' (length=3)
      1 => string 'Views' (length=5)

No x I have a array with N values

array (size=1)
      0 => 'a'
      1 => 'b'
      ...

And I want to add them to the first index of array x , while using array_merge I do not get the expected result:

array (size=1)
      0 => 
        array (size=2)
          0 => string 'App' (length=3)
          1 => string 'Views' (length=5)
      1 => 'a'
      2 => 'b'

When should it be:

array (size=1)
      0 => 
        array (size=2)
          0 => string 'App' (length=3)
          1 => string 'Views' (length=5)
          2 => string 'a'
...

Example:

$ranking[] = ['App', 'Views'];

$options[] = ['A', 'B'];

$merge = array_merge($ranking, $options);
$merge2 = array_merge($ranking[0], $options);

var_dump($merge);
var_dump($merge2);

Example on ideone

    
asked by anonymous 14.07.2016 / 18:55

2 answers

4

You should select the appropriate array (position 0 of array y) to merge:

$y[0] = array_merge($y[0],$x);
    
14.07.2016 / 19:04
3

With PHP5.6 you can simplify this assignment by combining array_push() and the operator eclipse ( ... ) , it unpacks each element of the array as an argument to push_array() , in practice the generated statement would be something like array_push($ranking[0], 'A', 'B', 'C')

Example - ideone

<?php
   $ranking[] = ['App', 'Views'];
   $options[] = ['A', 'B'];
   array_push($ranking[0], ...$options[0]);

   echo "<pre>";
   print_r($ranking);

Output:

Array
(
    [0] => Array
        (
            [0] => App
            [1] => Views
            [2] => A
            [3] => B
        )

)

Related:

What is the name of the operator ... used in PHP 5.6?

    
14.07.2016 / 20:22