Search code examples
phparraysfiltering

Get a subset of elements from a flat array starting from one value and ending at another value


If I have an array, for ex,

$numarray = array("abc", "def", "ghi", "jkl", "mno");

How can I select values in between the starting point and ending point. If the starting point is def and end point is jkl, then it should return ["def", "ghi" and "jkl"]. The starting and ending string is dynamic so it should match and then return the range of values.


Solution

  • This should work for you:

    Just take an array_slice() from your array.

    <?php
    
        $numarray = array("abc", "def", "ghi", "jkl", "mno");
        $start = "def";
        $end = "jkl";   
        $startPosition = array_search($start, $numarray);
        $endPosition = array_search($end, $numarray) - $startPosition + 1;
    
        print_r(array_slice($numarray, $startPosition, $endPosition));
    
    ?>
    

    output:

    Array
    (
        [0] => def
        [1] => ghi
        [2] => jkl
    )