Search code examples
phparraysrangesliceoffset

How to extract a range of elements between two specified keys?


I have two arrays, the first one is:

Array (
  [0] => Mar
  [1] => Jun
)

and the second one is:

Array (
  [Jan] => January
  [Feb] => February
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
  [Jul] => July 
  [Aug] => August
  [Sep] => September
  [Oct] => October
  [Nov] => November
  [Dec] => December
)

I'd like to extract the elements from the first nominated month to the second nominated month in the search array.

My expected result is:

Array (
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
)

Solution

  • Please check below answer, May be it will help you:

    $fullArray = [
        'Jan' => 'January',
        'Feb' => 'February',
        'Mar' => 'March',
        'Apr' => 'April',
        'May' => 'May',
        'Jun' => 'June',
        'Jul' => 'July',
        'Aug' => 'August',
        'Sep' => 'September',
        'Oct' => 'October',
        'Nov' => 'November',
        'Dec' => 'December',
    ];
    
    
    $arrayToCompare = [
        'Mar', 'Jun'
    ];
    
    
    
    $matchedArray = array();
    
    $matchedFirst = false;
    $matchedLast = false;
    
    foreach ($fullArray as $key => $value) {
        if ($key == $arrayToCompare[0]) {
            $matchedFirst = true;
        }
    
        if ($key == $arrayToCompare[1]) {
            $matchedLast = true;
        }
    
        if ($matchedFirst == true) {
            $matchedArray[$key] = $value;
        }
    
        if ($matchedLast == true) {
            $matchedArray[$key] = $value;
            break;
        }
    
    }
    
    print_r($matchedArray);
    die;