Question

I have encountered this in my php code. It all works and everything but I don't understand why the escape needs to be used. This produces a drop down menu of all the months.

foreach ($months as $key => $value) {
    echo "<option value \"$key\">$value</option>\n";

But so does this:

foreach ($months as $key => $value) {
    echo "<option value $key>$value</option>\n";

So I am confused as to why the escape is used? Sorry this might be really obvious but I am new to php?

Was it helpful?

Solution

Your second example does not work; it produces a Parse Error.

The quotes are escaped to indicate to PHP that you want to literally return the quotes rather than using the quotes to indicate the beginning or end of a string. In your first example, this works. In your second example, an error is produced because you're missing an operator (like a . to indicate concatenation) both before and after the $key variable.

UPDATE: You've updated your question, so I'll update my answer accordingly.

The difference now is that in your first example the quotes will print around $key, and in the second example quotes will not print around $key.

If $key contains a value without spaces, then there is no functional difference to the browser, they'll both create the drop-down the same way. But if $key contains spaces, this won't work correctly as only the characters before the space in $key will be sent as the value of the selected option.

Imagine the following HTML:

<option value="some value">Display</option>

Now without the quotes:

<option value=some value>Display</option>

Or with perhaps more attributes included:

<option value=some value selected>Display</option>

So you can see that this doesn't work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top