3
<select>
    <option>A</option>
    <option>B</option>
    <option>C</option>
    //...  and so on - till Z
</select>

is there any shorter way, something like:

$arr = alphabet;
foreach($arr as $el){
    echo "<option>" . $el . "</option>";
}

So, I need to avoid writing this:

$arr = array('A','B','C','D'... );
Qirel
  • 25,449
  • 7
  • 45
  • 62
qadenza
  • 9,025
  • 18
  • 73
  • 126

3 Answers3

6

You could use range "Create an array containing a range of elements":

$arr = range('A','Z');
foreach($arr as $el){
    echo "<option>" . $el . "</option>";
}
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
5

Just use range() with the limits A and Z. This creates the array with the characters defined in that range. Then all you need is to loop over it and print it!

<select>
<?php
foreach (range('A', 'Z') as $l) {
    echo '<option value="'.$l.'">'.$l."</option>\n";
}
?>
</select>

If you want to add other letters than A-Z, you are probably better off adding those manually - range() doesn't like characters outside the range of A-Z.

<select>
<?php
$alphabet = range('A', 'Z');
$alphabet[] = 'č';
$alphabet[] = 'ć';
$alphabet[] = 'š';
$alphabet[] = 'đ';
$alphabet[] = 'ž'; 
foreach ($alphabet as $l) {
    echo '<option value="'.$l.'">'.$l."</option>\n";
}
?>
</select>
Qirel
  • 25,449
  • 7
  • 45
  • 62
3

The others have shown range, but to get rid of the loop:

echo '<option>'.implode('</option><option>', range('A', 'Z')).'</option>';
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87