0

I am trying to unset array item in my multidimensional array. However the approach is working for only first loop (which is not my case) in second loop unset doesn't work.

I have tried to find here but unable to get the result with those resolution. So eventually posting with new thread.

$arr = [
    'subnav'  => [
        'first'  => [
            'one'   => 'hello',
            'two'   => 'Jatin',
            'admin' => TRUE,
        ],
        'second' => [
            'one'   => 'hello',
            'two'   => 'Priya',
            'admin' => FALSE,
        ],
    ],
    'pagenav' => [
        'cook'   => [
            'one'   => 'hello',
            'two'   => 'Rahul',
            'admin' => TRUE,
        ],
        'driver' => [
            'one'   => 'hello',
            'two'   => 'Vijay',
            'admin' => TRUE,
        ],
    ],
];

foreach ( $arr as $floop => $fval ) {

    foreach ( $fval as $nav => $item ) {
        if ( $item[ 'admin' ] == FALSE ) {
            unset( $fval[ $nav ] );
        }
    }
}

So here I want to remove every item which has admin => false

2 Answers 2

1

you try unset a variable not the array so try that

foreach ( $arr as $floop => $fval ) {

   foreach ( $fval as $nav => $item ) {
      if ( $item[ 'admin' ] == FALSE ) {
        unset( $arr[$floop][ $nav ] );
      }
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could try the following: (Not tested)

function unsetAdmin(&$array)
{
    foreach($array as $key => &$value) {
        if (is_array($value)) {
            unsetAdmin($value);
        }
        if (false === $value && $key == 'admin') {
            unset($array[$key]);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.