Reputation: 398
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',
];
Upvotes: 1
Views: 68
Reputation: 768
Hi you should use array_push emaple:
$names = [
'John',
'Bryan',
'Sersi',
];
if(somecondition){
array_push($names, 'Bobby', 'Nail');
}
var_dump($names);
Upvotes: 0
Reputation: 447
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.
Upvotes: 0
Reputation: 11
Try to use array_push()
function
$names = [
'John',
'Bryan',
'Sersi',
];
if(somecondition){
array_push($names, 'Bobby', 'Nail');
}
and then just call $names
again
Upvotes: 0
Reputation: 147246
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';
}
Upvotes: 1