If you are guaranteed unique values in the array, you could do array_flip to exchange the keys and values, and then array_filter, then array_flip again
$_a = array_flip($a);
$_a = array_filter($_a,function($val){
if(false === strpos($val,".")){
return true;
}
return false;
});
$a = array_flip($_a);
If not, you could use array_walk to null out the child values, then use array_filter. If null is a possible value for parents (or anything that resolves to false), then you can always choose your own to use for the children, and filter by that. If there isn't such a value you can use, this solution won't work.
$_a = $a;
array_walk($_a,function(&$val,$key){
if(false !== strpos($val,".")){
$val = null;
}
});
$a = array_filter($_a);
You could also use array_keys, array_filter, and array_intersect_keys. This will work regardless of whether the values are unique, and, unlike the second solution, will work if a parent value is null.
$_a = array_keys($a);
$_a = array_filter($_a,function($val){
if(false === strpos($val,".")){
return true;
}
return false;
});
$_a = array_flip($_a); //1=>foo, 2=>bar becomes foo=>1, bar=>2
$a = array_intersect_keys($a,$_a);
I know it's often preferable to use array functions when possible, but I'm not sure if any of the above solutions is going to be better than a simple foreach:
$_a = [];
foreach($a as $k=>$v){
if(false === strpos($k,".")){
$_a[$k] = $v;
}
}
However, your original question asked how to use array_filter, so I presented various options for utilizing it. As others have stated, though, if you need to filter based on the value of the key, there is no way to do that with JUST array_filter