PHP: remove element from multidimensional array (by key) using foreach

suz picture suz · Dec 15, 2014 · Viewed 21.1k times · Source

I got multidimensional array. From each subarray, I would like to remove / unset values with index 1. My array $data.

Array
(
    [3463] => Array
        (
            [0] => 1
            [1] => 2014
            [context] => 'aaa'
        )

    [3563] => Array
        (
            [0] => 12
            [1] => 2014
            [context] => 'aaa'
        )       

    [2421] => Array
        (
            [0] => 5
            [1] => 2014
            [context] => 'zzz'
        )               
)

I would like to remove every element with index '1' from subarrays. Desired output is:

Array
(
    [3463] => Array
        (
            [0] => 1
            [context] => 'aaa'
        )

    [3563] => Array
        (
            [0] => 12
            [context] => 'aaa'
        )       

    [2421] => Array
        (
            [0] => 5
            [context] => 'zzz'
        )               
)

Why this does not work?

foreach ($data as $subArr) {
   foreach ($subArr as $key => $value) {
       if ($key == '1') {
        unset($subArr[$key]);
       }

   }
}

I'm sorry if this problem is trivial for you guys.

Answer

Pouya Darabi picture Pouya Darabi · Dec 15, 2014

easy way!? you can do this just with one foreach!

foreach ($data as $key => $subArr) {
    unset($subArr['1']);
    $data[$key] = $subArr;  
}