Filtering an array in php, having both value- and key-related conditions
I'm trying to filter an array, in which the filter function is supposed to check for multiple conditions. For example, if element x starts with a capital letter, the filter function should return true. Except, if the element before element x satisfies certain other开发者_JAVA百科 conditions, then element x should not stay in the array and the filter function should therefore return false.
Problem is that the callback function in array_filter only passes the element's value and not its key... doing some magic with array_search will probably work, but I was just wondering whether I'm looking in the wrong place for this specific issue?
Sounds like a case for a good old foreach loop:
foreach ($arr as $k => $v) {
// filter
if (!$valid)
unset($arr[$k]);
}
$newArray=array();
foreach($oldArray as $key=>$value){
if(stuff){
$newArray[$key]=$value;
}
}
or
foreach($array as $key=>$value){
if(stuff){
unset($array[$key]);
}
}
Did you use simple foreach?
$prev;
$first = true;
$result = array();
foreach ($array as $key => $value)
{
if ($first)
{
$first = false;
// Check first letter. If successful, add it to $result
$prev = $value;
continue; // with this we are ignoring the code below and starting next loop.
}
// check $prev's first letter. if successful, use continue; to start next loop.
// the below code will be ignored.
// check first letter... if successful, add it to $result
}
精彩评论