echo '<option value='+$index+'>'+$county[$index];
It is PHP code. It doesn't output what I want. Any idea?
echo '<option value='+$index+'>'+$county[$index];
It is PHP code. It doesn't output what I want. Any idea?
To concatenate text in PHP use the .
operator not the +
echo '<option value='.$index.'>'.$county[$index];
You can read more about the .
and the .=
operators if you want: String Operators
Try this:
echo '<option value=' . $index . '>' . $county[$index];
You can even do this way too:
echo "<option value={$index}>{$county[$index]}";
Use either:
echo '<option value=' . $index+'>' . $county[$index];
or
echo "<option value='$index'>$county[$index]";
echo '<option value="', $index, '">', $country[$index];
echo "<option value='$index'>$country[$index]";
printf('<option value="%s">%s', $index, $country[$index]);
There are other, additional ways (sprintf and echo, for one) that accomplish the same thing.
Take your pick.
Personally, I would use the first example, because echo takes multiple arguments.
With the echo
statement, unlike with other things in PHP, you can also use a ,
to concatenate. It's said to be faster than the .
echo '<option value=' , $index , '>' , $county[$index];
Apart from the concatenation operator being .
... PHP is a templating language. Use it, don't fight it! Avoid handling HTML in strings; let PHP itself do it.
And when you output arbitrary text, remember to HTML-escape it, to avoid cross-site-scripting problems. eg.:
<?php
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
?>
...
<select name="county">
<?php for ($i= 0; $i<count($county); $i++) { ?>
<option value="<?php h($i); ?>">
<?php h($county[$i]); ?>
</option>
<?php } ?>
</select>