开发者

What is wrong with this statement echo '<option value='+$index+'>'+$county[$index];?

echo '<option value='+$in开发者_开发知识库dex+'>'+$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]";


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];


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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜