I have an array :
$main_arr = [
0=>[
"el 01",
"el 02",
"el 03",
],
1=>[
"el 11",
"el 12",
"el 13",
],
2=>[
"el 21",
"el 22",
"el 23",
],
];
Is there a function or single statement in php like ninja_array_method($main_arr, "el new") that add new element into all sub arrays to be :
$main_arr = [
0=>[
"el 01",
"el 02",
"el 03",
"el new",
],
1=>[
"el 11",
"el 12",
"el 13",
"el new",
],
2=>[
"el 21",
"el 22",
"el 23",
"el new",
],
];
I just want to add these element "el new" into all arrays without any change in one single line or just method like add_el($main_arr, "el new")
Use foreach loop with reference &:
foreach($data as $ind=>&$ar){
$ar[] = 'el new';
}
Demo
Reference & mutates your subarray.
If you need a function:
function add_el($data,$elem){
foreach($data as $ind=>&$ar){
$ar[] = $elem;
}
return $data;
}
Demo
if you are familiar with laravel collection
You can use push Method
$main_arr = [
0=>[
"el 01",
"el 02",
"el 03",
],
1=>[
"el 11",
"el 12",
"el 13",
],
2=>[
"el 21",
"el 22",
"el 23",
],
];
$expectedArray = [
0=>[
"el 01",
"el 02",
"el 03",
"el new",
],
1=>[
"el 11",
"el 12",
"el 13",
"el new",
],
2=>[
"el 21",
"el 22",
"el 23",
"el new",
],
];
$collection = collect($main_arr)
->map(function($eachArray){
return collect($eachArray)->push('el new')->toArray();
})
->toArray();
dd($expectedArray,$collection);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With