Search code examples
phparraysfiltering

Receive values from array between other values


I have array, for example:

$array = (5, 2, 17, 9, 12, 6);

and always two values - $first and $last. I would like get all values from $array between $first and $last.

For example:

$first = 2;
$last = 6;

I would like receive:

$receive = array(17, 9, 12);

For example:

$first = 5;
$last = 9;

I would like receive:

$receive = array(2, 17);

Solution

  • Search and slice:

    $receive = array_slice($array,
                                  $s=array_search($first, $array)+1,
                                     array_search($last, $array)-$s);