2

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

0

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

no its just a map and push. Collection has lots and lot of functions
1

If you want a one-liner here's a few options:

In place

$value = 'el new';
array_walk($main_arr, function (&$entry) use ($value) { $entry[] = $value; });

Immutable initial array

$value = 'el new';
$modified = array_map(function ($entry) use ($value) { return array_merge($entry, [$value]); }, $main_arr);

Immutable with a bit of array_map trickery

$value = 'el new';
$modified = array_map(function ($entry, $value) { return array_merge($entry, [$value]); }, $main_arr, array_fill(0, count($main_arr), $value));

The sky is the limit

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.