JorenB
JorenB

Reputation: 1831

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 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?

Upvotes: 1

Views: 1446

Answers (3)

Valour
Valour

Reputation: 810

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
}

Upvotes: 1

Denis de Bernardy
Denis de Bernardy

Reputation: 78463

Sounds like a case for a good old foreach loop:

foreach ($arr as $k => $v) {
  // filter
  if (!$valid)
    unset($arr[$k]);
}

Upvotes: 1

Robus
Robus

Reputation: 8259

$newArray=array();
foreach($oldArray as $key=>$value){
   if(stuff){
      $newArray[$key]=$value;
   }
}

or

foreach($array as $key=>$value){
   if(stuff){
      unset($array[$key]);
   }
}

Upvotes: 1

Related Questions