1

for example this is my current array

$names[] = [
   'John',
   'Bryan',
   'Sersi',
];

I want to add new values in some conditions like

if(somecondition){
   $names[] = [
      'Bobby',
      'Nail',
   ]
}

So the final array would be like this

$names[] = [
   'John',
   'Bryan',
   'Sersi',
   'Bobby',
   'Nail',
];
2
  • May I know if the first code is your initialization or an update to the current array? Commented Feb 13, 2019 at 3:39
  • print_r(array_merge($names[0], $secondNames[0])); Commented Feb 13, 2019 at 3:51

4 Answers 4

1

You need to use array_merge to add the new elements at the same level in the array. Note that you shouldn't use [] after $names in your initial assignment (otherwise you will get a multi-dimensional array):

$names = [
   'John',
   'Bryan',
   'Sersi',
];
if(somecondition){
   $names = array_merge($names, [
      'Bobby',
      'Nail',
   ]);
}

If you need to add the names using [] you can add them one at a time:

if(somecondition){
   $names[] = 'Bobby';
   $names[] = 'Nail';
}
Sign up to request clarification or add additional context in comments.

12 Comments

array ( 0 => 'arr1', 1 => 'arr1', 2 => 'arr1', 3 => 'arr1', 4 => 'arr1', 5 => 'arr1', ), 1 => 'arr12', 2 => 'arr12', 3 => 'arr12', 4 => 'arr12', )
I just merged nested
Did you see the change I made to your initial assignment as well? (remove the [] in that line)
Is there another way? because I have to use [].
Why do you have to use []?
|
0

Try to use array_push() function

$names = [
   'John',
   'Bryan',
   'Sersi',
];
if(somecondition){
   array_push($names, 'Bobby', 'Nail');
}

and then just call $names again

Comments

0

New values can be added in array using [] or using array_push as well. using array_push:

$names = [
   'John',
   'Bryan',
   'Sersi',
];
if(somecondition){
   array_push($names, 'Bobby', 'Nail');
}

using [] you can add them one at a time:

$names = [
   'John',
   'Bryan',
   'Sersi',
    ];
if(somecondition){
   $names[] = 'Bobby';
   $names[] = 'Nail';
}

A small comparison between array_push() and the $array[] method, the $array[] seems to be a lot faster.

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    $array[] = $x;
}
?>
//takes 0.0622200965881 seconds

and

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    array_push($array, $x);
}
?>
//takes 1.63195490837 seconds

so if your not making use of the return value of array_push() its better to use the $array[] way.

Comments

0

Hi you should use array_push emaple:

    $names = [
       'John',
       'Bryan',
       'Sersi',
    ];

    if(somecondition){
       array_push($names, 'Bobby', 'Nail');
    }

var_dump($names);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.