phparrayskeyfiltering

Get all keys in a flat array from a qualifying value until before the second occurrence of a qualifying value


My switch case allows me to find the values which match one of a list of values

I need to extend this code/logic so that I can collect all consecutive keys starting from the first occurring C or D until the element before the second occurring C or D.

Here is what I would like to do:

foreach ($array as $key => $value) {
    switch($value) {
        case "C": 
        case "D":
        // Store all keys from "C" until I come across a second value "C" or "D"
    }
}

Here is an example:

$array =
 (
      [53] => q
      [61] => f
      [74] => s
      [87] => C
      [19] => D
      [101] => e
      [22] => C
      [13] => h
 )

Result: "87 19 101"


Solution

  • This is a weird logic, but this should work:

    //Triggers are the flags that trigger opening or close of filters
    $triggers = array('C', 'D');
    $filtered = [];
    $stack = [];
    
    foreach($array as $k => $v) {
    
        //If the trigger is opened and I see it again, break the loop
        if (in_array($v, $stack)) {
            break;
        }
    
        //If we sees the trigger OR the stack is not empty (we are opened)
        //continuously pull the keys out
        if (in_array($v, $triggers) || !empty($stack)) {
            $stack[] = $v;
            $filtered[] = $k;
        }
    }
    

    The output for this is

    Array
    (
      [0] => 87
      [1] => 19
      [2] => 101
    )