Hello friends. The problem I am having with the below code is something that probably has a straight forward answer, to be honest. I just don't fully understand why double and single quotes are used in the following lines (in the code below):

echo ‘<div class=”map” style=”width: ‘ . $mapSize . ‘em;”><pre>’;

..... and its closing tags:

echo “</pre></div>\n”;

The full code of the script is below, but i just don't get why the opening div and pre tags (shown above) are echoed using single quotes and their closing tags are echoed using double quotes?

Furthermore, i don't understand how $mapSize (above) can even be parsed if it is being echoed in single qoutes?

The below code is an extract from a book i am reading. It is supposed to be a simple simulation of a bird flying home

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>Homing Pigeon Simulator</title>
<link rel=”stylesheet” type=”text/css” href=”common.css” />
<style type=”text/css”>
div.map { float: left; text-align: center; border: 1px solid #666;
background-color: #fcfcfc; margin: 5px; padding: 1em; }
span.home, span.pigeon { font-weight: bold; }
span.empty { color: #666; }
</style>
</head>
<body>

<?php

$mapSize = 10;

// Position the home and the pigeon

do {
$homeX = rand ( 0, $mapSize-1 );
$homeY = rand ( 0, $mapSize-1 );
$pigeonX = rand ( 0, $mapSize-1 );
$pigeonY = rand ( 0, $mapSize-1 );
} while ( ( abs( $homeX - $pigeonX ) < $mapSize/2 ) && ( abs( $homeY -
$pigeonY ) < $mapSize/2 ) );

do {

// Move the pigeon closer to home

if ( $pigeonX < $homeX )
$pigeonX++;
elseif ( $pigeonX > $homeX )
$pigeonX--;
if ( $pigeonY < $homeY )
$pigeonY++;
elseif ( $pigeonY > $homeY )
$pigeonY--;

// Display the current map

echo ‘<div class=”map” style=”width: ‘ . $mapSize . ‘em;”><pre>’;
for ( $y = 0; $y < $mapSize; $y++ ) {
for ( $x = 0; $x < $mapSize; $x++ ) {
if ( $x == $homeX && $y == $homeY ) {
echo ‘<span class=”home”>+</span>’; // Home
} elseif ( $x == $pigeonX && $y == $pigeonY ) {
echo ‘<span class=”pigeon”>%</span>’; // Pigeon
} else {
echo ‘<span class=”empty”>.</span>’; // Empty square
}
echo ( $x != $mapSize - 1 ) ? “ “ : “”;
}
echo “\n”;
}
echo “</pre></div>\n”;

} while ( $pigeonX != $homeX || $pigeonY != $homeY );

?>
</body>
</html>

    First issue: the code you pasted here is using "directional" quotes, which won't do what you want them to do in PHP or HTML, where you need to use "straight" quote.

    You want to use "these" or 'these', but NOT “these” nor ‘these’.
    
    (There are, however, certain situations that have nothing to do 
    with this type of quoting where `this` would be used, 
    but ignore that for now.)
    

    Anyway, whichever type of "straight" quotes you use -- double or single -- to start a string literal is what you need to use to end it. The other type of quote is then treated as just another character within the string. If you want to have the same type of quote that started it used within the string, then you have to escape it.

    echo "This here's a \"double-quoted\" string with both types of quotes inside it.";
    echo 'This here\'s a "single-quoted" string with both types of quotes inside it.';
    

    There is one important difference between which type of quote you use to delimit the string, however: variables are interpolated within a double-quoted string but not within a single-quoted string, plus double-quoted strings allow the use of some special escape sequences.

    <pre>
    <?php
    $foo = "World";
    echo "Hello, $foo\n";
    echo 'Hello, $foo\n';
    ?>
    </pre>
    

    Output:

    Hello, World
    Hello, $foo\n
    

      NogDog, your single-quote example ends with a double-quote. 🙂

        Bonesnap;11047875 wrote:

        NogDog, your single-quote example ends with a double-quote. 🙂

        Added the missing semi-colons, too. 🙂

          Plus HTML doesn't care which you use :
          <div class="map"> is the same as <div class='map'>

            cretaceous;11047891 wrote:

            Plus HTML doesn't care which you use :
            <div class="map"> is the same as <div class='map'>

            I would modify that to say "most browsers that render HTML don't really care if you use single or double quotes BUT based on my experience, you should probably always use double quotes or you'll run into trouble with finicky validators and possibly javascript"

              Yep, I wondered about mentioning the javascript issue, but I've not yet found a page not validating due to that.
              Maybe I will soon!

                I'm having a hard time remembering where I've run into trouble with single quotes in HTML. This comes to mind:

                $str = "'";
                var_dump(htmlspecialchars($str));

                The [man]htmlspecialchars[/man] function does not recognize a single quote as a 'special char.'

                  sneakyimp;11047911 wrote:

                  I'm having a hard time remembering where I've run into trouble with single quotes in HTML. This comes to mind:

                  $str = "'";
                  var_dump(htmlspecialchars($str));

                  The [man]htmlspecialchars[/man] function does not recognize a single quote as a 'special char.'

                  From that manual page:

                  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.

                  • "'" (single quote) becomes '&#039 ;' (or &apos😉 only when ENT_QUOTES is set.

                    Ok fine fine. I don't recall using the ENT_*QUOTES constants ever myself, perhaps that's my fault.

                    The one other good reason that comes to mind is when specifying javascript as part of an HTML attribute. If you specify any strings in the javascript, you must be careful to make sure you escape your quotes in the right way. e.g.

                    <a href="#" onclick="alert('hello world');">CLICK ME</a>

                    That should work because the single and double quotes don't get confused. This breaks:

                    <a href="#" onclick="alert("hello world");">CLICK ME</a>

                    Obviously this doesn't argue in favor of single or double quotes, but does suggest one should be consistent.

                    Also, on every major site where I've bothered to look, double quotes are always used. Is this preponderance of usage a good case?

                      Thanks for all the responses (above), although i still don't feel like i have any clarity on my question.

                      To elaborate, the opening and closing tags (below):

                      echo &#8216;<div class=&#8221;map&#8221; style=&#8221;width: &#8216; . $mapSize . &#8216;em;&#8221;><pre>&#8217;;

                      echo &#8220;</pre></div>\n&#8221;;

                      ........... need to have single quotes on either side of the opening one and double on either side of the closing one, in order for them to even work.

                      Can someone just explain to me in leyman's terms why it needs to be so specific, and it needs to be single quotes for one and double for the other?

                      Paul.

                        Maybe.

                        You have to define "work". (Or, 'work', in the phrase 'in order for them to even work.')

                        The reason you need double quotes to make the second one "work" is, ostensibly that you want a UNIX Newline character instead of the literal string '\n' to be printed. In php, "\n" is a LF (Unix Newline) character, and '\n' is a backslash-followed-by-the-lowercase-letter-n.

                        The reason you need to use single quotes for the top example is because the string contains double quotes. You could, just as easily, do this instead:

                        echo "<div class='map' style='width: " . $mapSize . "em;'><pre>";

                        That's pretty much what NogDog said way up there ....

                          NogDog;11048009 wrote:

                          I've never seen any HTML break because one quote type or the other was used for attribute values within tags, and the HTML 4.01 spec. for attributes says either is okay.

                          I've often suspected that while either is allowed, the preference was for double quotes to be used. HTML 4 does after all provide a named character reference [font=monospace]&quot;[/font] for escaping double quotes, but not for single quotes, requiring the numeric entity to be used instead; when I was looking into this, most browsers recognised [font=monospace]&apos;[/font] but IE was not one of them.

                            Paul help!;11048011 wrote:

                            Thanks for all the responses (above), although i still don't feel like i have any clarity on my question.

                            To elaborate, the opening and closing tags (below):

                            echo &#8216;<div class=&#8221;map&#8221; style=&#8221;width: &#8216; . $mapSize . &#8216;em;&#8221;><pre>&#8217;;

                            echo &#8220;</pre></div>\n&#8221;;

                            ........... need to have single quotes on either side of the opening one and double on either side of the closing one, in order for them to even work.

                            Can someone just explain to me in leyman's terms why it needs to be so specific, and it needs to be single quotes for one and double for the other?

                            Paul.

                            Seems to me the fundamental concept escaping you is how to define strings properly in PHP. The idea requires one to understand what is correct syntax and incorrect syntax when defining strings in PHP.

                            For starters, if you want to define a string containing a single quote in PHP, you cannot do this because it's invalid PHP syntax:

                            // this will not work because it makes 'broken' PHP
                            $my_var = ''';
                            

                            Basically the PHP parser doesn't understand that you want to make a string with a single quote in it because you are using single quotes to denote the start and end of your string. If you insist on using single quotes, you must escape the single quotes inside that string to avoid having broken PHP syntax:

                            // this should work because you have escaped the single quote inside your string with a backslash (\)
                            $my_var = '\'';
                            

                            Alternatively, if you use double quotes to denote the beginning and end of your string, you don't need to escape any single quote chars in the string:

                            $my_var = "'";
                            

                            As a general rule, if I must define a string with single quotes in it, I usually use double quotes around the string. If I want to have double quotes in the string, I use single quotes around it. You should probably read up a bit on PHP strings.

                              Thank you.

                              This helps clarify things a lot.

                              I just need to ask 2 more things.

                              1) So the second line needs double quotes so /n can be parsed? is this correct?

                              echo “</pre></div>\n”;

                              2) How can $mapSize in the first line be parsed if it is surrounded by single quotes? is it because of the outer double quotes which are part of the style attribute?

                              echo ‘<div class=”map” style=”width: ‘ . $mapSize . ‘em;”><pre>’;

                                Paul help!;11048039 wrote:

                                Thank you.

                                Certainly. Please pay it forward!

                                Paul help!;11048039 wrote:

                                1) So the second line needs double quotes so /n can be parsed? is this correct?

                                echo “</pre></div>\n”;

                                That looks like valid PHP to me. Did you test it? Put it in a script and run it and see if it works. Proof of the pudding is in the tasting.

                                Also \n and /n are not the same thing. \n is used to create a newline character in a double-quoted string. I suggest you try experimenting a bit. Also keep in mind that HTML tends to render newline chars as spaces and usually renders multiple spaces in your HTML source as a single space in the output.

                                Paul help!;11048039 wrote:

                                2) How can $mapSize in the first line be parsed if it is surrounded by single quotes? is it because of the outer double quotes which are part of the style attribute?

                                echo ‘<div class=”map” style=”width: ‘ . $mapSize . ‘em;”><pre>’;

                                You should see that this line defines not just one but two single-quoted strings. The first one is

                                ‘<div class=map” style=”width: ‘

                                and the second one is

                                ‘em;”><pre>’/code]
                                that single quote after width: ends the first string then you have a period (which is the concatenation operator for strings in PHP) followed by $mapSize, another period to concatenate, and then the final string. Think of it as:
                                [code=php]echo "string1" . $myvar . "string2";

                                  By the way, all of this would be much easier to understand if you had a good Integrated Development Environment (IDE) or a decent code editor. It will highlight your PHP code as you type and point out when you make syntax errors. I use Eclipse PDT.

                                    sorry.

                                    what i meant to ask was:

                                    1) So the second line needs double quotes so \n can be parsed? is this correct?

                                    echo &#8220;</pre></div>\n&#8221;;

                                    ... so is this correct?

                                      Paul help!;11048045 wrote:

                                      sorry.

                                      what i meant to ask was:

                                      1) So the second line needs double quotes so \n can be parsed? is this correct?

                                      echo &#8220;</pre></div>\n&#8221;;

                                      ... so is this correct?

                                      It looks like valid PHP except maybe you have some kind of weird special double quote character. I can't really tell because you are not using the correct code formatting tags. Please do so.

                                      Also, I'll reiterate two prior statements:
                                      1) test it yourself and see if it works
                                      2) get a decent code editor and your life will be much easier.

                                        Write a Reply...