2

Currently my code shows the year from 1885 to 2017. What this does is show the years like so 0 = 1885, 1 = 1886.

What I want is that it shows it like this 1885 = 1885, 1886 = 1886 etc. (This resembles the date a car is built)

$options = [];
for ($x = 1885; $x <= date("Y"); $x++) {
array_push($options, $x);
}

  echo $this->Form->select('year', [
       $options,
   ],[
     'label' => false,
     'class' => 'form-group form-control',
   ]);

So I was wondering how to fix what I did wrong.

0

3 Answers 3

3
for ($x = 1885; $x <= date("Y"); $x++) {
    $options[$x] = $x;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. Also, you made script load faster by removing array_push call and using a language construct to append array variable.
2

You can also do this using range() and array_combine():-

$years = range(1985, date('Y'));
$options = array_combine($years, $years);

Comments

1

You need to set the keys of the $options array as the keys are used as values to be submitted. You can as well benefit from using the range function to generate the array:

$values = array_map('strval', range(1885, (int) date("Y")));
$options = array_combine($values, $values);

2 Comments

The first answer works better for me, it's less complicated. But still I appreciate your answer!
yes, the first answer is easier to read, you could unroll the example I give here a little to make it more readable.

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.