简体   繁体   中英

Add new values in array PHP

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',
];

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';
}

Try to use array_push() function

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

and then just call $names again

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.

Hi you should use array_push emaple:

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

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

var_dump($names);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM