Beldion
Beldion

Reputation: 331

How to push data into an array which has already been pushed into another array?

Is there a way where I can insert $dialstack inside of $menustack after putting menustack inside of $mainstack?

The outcome that I want is possible by moving array_push($mainstack, $menustack); to the last line, but I am really looking for a way where I can just insert an array to an existing stack of arrays.

$mainstack = ['applet' => "Flow"];

$menustack = ['applet' => "Menu", 'repeat' => "2"];

$dialstack = [];

$dial1 = ['applet' => "Dial", 'number' => "165465468", 'whisper' => "Yes"];
$dial2 = ['applet' => "Dial", 'number' => "654984", 'whisper' => "No"];
$dial3 = ['applet' => "Dial", 'number' => "398965165", 'whisper' => "Yes"];

array_push($mainstack, $menustack);
array_push($dialstack, $dial1);
array_push($dialstack, $dial2);
array_push($dialstack, $dial3);
array_push($menustack, $dialstack);

Upvotes: 2

Views: 179

Answers (3)

mickmackusa
mickmackusa

Reputation: 47864

array_push() is only uniquely helpful when you want to push multiple entries into a previously declared array. It is notably unhelpful when you would like to push a reference into an array or want to push an item into a not-yet-declared array. For this reason, I recommend that you not use array_push() in two places and only use array_push() when adding multiple items to an array.

By pushing $menustack into $mainstack by reference, you don't need to remember/guess/calculate the required index to later assign more data to it. $menustack[] allows you to push an additional entry into its relative location in the $mainstack array. Demo

$mainstack[] =& $menustack;
array_push($dialstack, $dial1, $dial2, $dial3);
$menustack[] = $dialstack;
var_export($mainstack);

Output:

array (
  'applet' => 'Flow',
  0 => 
  array (
    'applet' => 'Menu',
    'repeat' => '2',
    0 => 
    array (
      0 => 
      array (
        'applet' => 'Dial',
        'number' => '165465468',
        'whisper' => 'Yes',
      ),
      1 => 
      array (
        'applet' => 'Dial',
        'number' => '654984',
        'whisper' => 'No',
      ),
      2 => 
      array (
        'applet' => 'Dial',
        'number' => '398965165',
        'whisper' => 'Yes',
      ),
    ),
  ),
)

Upvotes: 0

Hamza Zafeer
Hamza Zafeer

Reputation: 2436

array_push($mainstack,array_merge($menustack,$dialstack));
print_r($mainstack);

First merge two arrays using array_merge then push them in $mainstack

Upvotes: 1

mbbentz
mbbentz

Reputation: 56

You just need to know the index of $menustack inside of $mainstack

$arrayOne = [];
$arrayTwo = [];
$arrayThree = [];

// $arrayOne goes inside of $arrayTwo
array_push($arrayTwo, $arrayOne);

// $arrayThree goes inside of $arrayTwo[0] which is $arrayOne
array_push($arrayTwo[0], $arrayThree);

var_dump($arrayTwo);

Upvotes: 3

Related Questions