1

I have an array() of years, they are in order lowest to highest, they are not sequential, so 1100, 1295, 1733,1734, 1980 etc. The key starts at 0 up to the number of years. So [0] => 1100, [1] => 1295.. [5] => 1980. What i am trying to do is pull a range out from the middle, so a user inputs start year = 1200 and end year = 1900. Can anyone help me create a new array from my original array with values that are between the start and end years. Thanks for your help. I am using PHP version 5.6+ cant remember the exact version.

6
  • 1
    Have a look at the array_search() function to identify your start and end keys, and then at array_slice() to extract the range if the user inputs exact values from your array; or even array_filter() to extract the values between start and end dates Commented Jan 15, 2018 at 20:20
  • do you have every year in your array, or only some years? Commented Jan 15, 2018 at 20:21
  • rtfm only some, not sequential. Mark Baker; ok I see where your going with that, like searching a string gettng the length then doing a string length on it..... hmmm Commented Jan 15, 2018 at 20:24
  • No, that is not what Mark said, but that is also a possibility. Implode, regex/strpos, explode Commented Jan 15, 2018 at 20:30
  • array_filter() has lead me to this stackoverflow question which looks promising. Dont want to waste anyone elses time. stackoverflow.com/questions/6174760/… Commented Jan 15, 2018 at 20:31

1 Answer 1

2

I think array_filter with a custom callback is the shortest way to get the time span:

$array = [1100, 1295, 1733, 1734, 1980];
$start = 1200;
$end = 1733;
$result = array_filter($array, function ($value) use ($start, $end) 
  {return $start <= $value && $value <= $end;});
var_dump($result);

But there are many other ways.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I am checking it out on my server, cheers ;) Building a timeline of historic caving events.. Bring on the darkness!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.