For example, i have the following multidimensional array (an array of associative arrays):
array(
[0]=> (array('key01'=>'value01', 'key02'=>'value02')),
[1]=> (array('key11'=>'value11', 'key12'=>'value12')),
[2]=> (array('key21'=>'value21', 'key22'=>'value22')),
...
[N]=> (array('keyN1'=>'valueN1','keyN2'=>'valueN2'))
);
I'm looking for a native method (if exists) that find a value in that array and remove the corresponding row. For example, i would remove row that contains value value21, the resulting array is the following:
array(
[0]=> (array('key01'=>'value01', 'key02'=>'value02')),
[1]=> (array('key11'=>'value11', 'key12'=>'value12')),
...
[N]=> (array('keyN1'=>'valueN1','keyN2'=>'valueN2'))
);
(i would not use for loops if possible...)
You can use array_filter() with closure to achieve this.
$myArr = array(
array('key01'=>'value01', 'key02'=>'value02'),
array('key11'=>'value11', 'key12'=>'value12'),
array('key21'=>'value21', 'key22'=>'value22'),
);
$finalArr = array_filter($myArr,function($val1){
$flag = true;
array_filter($val1,function($val2) use(&$flag){
if($val2 == 'value21'){
$flag=false;
}
});
return $flag;
});
$finalArr = array_values($finalArr); // to get the array numerically indexed in order
But I will have to say that doing a nested foreach
with unset()
is almost similar. Hope it helps.
Edit:
in_array() in the closure is much simpler
$finalArr = array_filter($myArr,function($val1){
return ! in_array("value21",$val1);
});
Also remember that there is no use of closure here rather lambda, both of them are anonymous functions.