Reputation: 9293
<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'... );
Upvotes: 3
Views: 284
Reputation: 78994
The others have shown range
, but to get rid of the loop:
echo '<option>'.implode('</option><option>', range('A', 'Z')).'</option>';
Upvotes: 3
Reputation: 26460
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>
Upvotes: 6
Reputation: 15131
You could use range "Create an array containing a range of elements":
$arr = range('A','Z');
foreach($arr as $el){
echo "<option>" . $el . "</option>";
}
Upvotes: 6