Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an element into subarray in php [duplicate]

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")

like image 425
Abdullah Al_Nahhal Avatar asked Feb 28 '26 08:02

Abdullah Al_Nahhal


2 Answers

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

like image 160
Aksen P Avatar answered Mar 02 '26 14:03

Aksen P


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);
like image 35
ManojKiran Appathurai Avatar answered Mar 02 '26 14:03

ManojKiran Appathurai