0

I have array as follows,

$arr['fixed_key'][0]['key1']['key2'] = 'y';
$arr['fixed_key'][1]['key1']['key2'] = 'y';
$arr['fixed_key'][2]['key1']['key2'] = 'n';
$arr['fixed_key'][3]['key1']['key2'] = 'n';

I want to remove all arrays which have key2='n', I can traverse through array in a loop and achieve this, as follows:

$l=length($arr);
for($i=0;$i<$l;$i++) {

    if($arr['fixed_key'][$i]['key1']['key2'] == 'n') {

        unset($arr['fixed_key'][$i]['key1']['key2']);

    }

}

My question is, is it possible to do this in better way, like array_map or array_walk, what is the best possible way?

1
  • you will do it with array_map and array_walk but you want to unset it in that functions also Commented Jan 7, 2016 at 5:21

2 Answers 2

3

You can use array_filter

$arr['fixed_key'][0]['key1']['key2'] = 'y';
$arr['fixed_key'][1]['key1']['key2'] = 'y';
$arr['fixed_key'][2]['key1']['key2'] = 'n';
$arr['fixed_key'][3]['key1']['key2'] = 'n';

$filtered = array_filter($arr['fixed_key'], function ($val) { return $val['key1']['key2']  !== "n"; });
Sign up to request clarification or add additional context in comments.

Comments

1

We can achive by using array_search() and unset, try the following:

if(($key = array_search($del_value, $arr)) !== false) {
        unset($arr[$key]);
 }

2 Comments

Nope you can't this'll work single dimensional array and not for multidimensional array
@Uchiha You are right, besides that, we also don't wanna traverse in the inner dimensions unnecessarily. Nimshad Abdul's solution looks good. We can't use unset($arr) inside arrap_map function, so array_filter is the best choice to go to.

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.