SitePoint Sponsor

User Tag List

View Poll Results: Single quotes or double quotes?

Voters
90. You may not vote on this poll
  • Single quotes

    45 50.00%
  • Double quotes

    11 12.22%
  • Mixed

    34 37.78%
  • Neither

    0 0%
Page 1 of 3 123 LastLast
Results 1 to 25 of 72
  1. #1
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,094
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)

    Quoting strings: what do YOU do?

    As you all probably know, there are different types of string quoting in PHP.
    Let's start with single quote vs double quote:

    PHP Code:
    $bar "foo";
    print 
    "hello $bar"// prints "hello foo"
    print 'hello $bar'// prints "hello $bar" 
    The double quotes replace variables with the value of the variables within the strings, while the single quotes don't.

    PHP Code:
    print "test"// prints "test"
    print 'test'// also prints "test"
    print test// assuming 'test' is not defined as a constant, also prints "test" 
    The result of all three statements is the same, but the interpreter doesn't see it thay way. The last one (print test is definitely the worst, because the compiler will first have to check if 'test' is a defined constant, and only after it figures out this isn't the case, will it print the string "test".
    The first example (print "test" also isn't great, because the interpreter has to scan the whole string for occurrences of variables. For this short string this isn't any problem, but for larger strings it might become noticeable.

    For these reason I personally ALWAYS stick to single quotes.
    What do you use?
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    That's an interesting question, heres what I found.

    When starting out everything was in a print statement.

    $name = "Earl"
    print("My name is $name");

    I mean every single line of HTML. It seemed flawless because it was a discipline I could remember, it was simple and it worked. I rarely come across remaining old code, but sometimes I do, and I groan. Still, not having to debug my print statements left me free to debug everything else I was doing wrong.

    Slowly I started to use echo and single concatenated quotes, mostly after reading posts on this subject on this forum.

    echo 'My name is ' . $name ;

    I found this made my vars easier to spot, and was much influenced by the fact I was learning OOP - which generally speaking, should return data, not echo or print output directly.

    I went down the road of comma separated echos for a while:

    echo 'My name is ', $name ;

    Which is even faster ... wheeee ....

    But, I found it harder to be consistent, so I stopped using that.

    Then of course Heredoc came out, so monster blocks of code including Javascript (wow!) could finally be injected into your page as is.

    So given that I am now layering my applications, generally speaking, not outputting much html directly, I allow myself the freedom to use both single and double quotes as and when the situation suits me. for example a pile of vars to go in a string:

    echo "The $size $feline $posture on the $product." ;

    ( the fat cat sat on the mat )

    rather than

    echo 'My name is ' . $name ;

    Maybe my "readability imperative" is now to do with the flow of data rather than the html.

    Choosing single or double quotes is often governed by where its headed, if its back into an Ajax-driven DOM then its often singles inside doubles to minimise all the inevitable backslashing crap.

    So when starting out pick one method and stick to it for a while. Train your editor to create the text with a shortcut key.

    But when you gain confidence and knowledge, experiment, and don't be afraid to use both/ether.

    Eventually this becomes a non-issue as you tend to output very little to the the page, or that output goes into some kind of placeholder, such as a template.
    Last edited by Cups; Sep 29, 2008 at 02:36. Reason: consistent not read ....

  3. #3
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,094
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    Thanks for your reply Cups, very nice explanation ! I appreciate it
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  4. #4
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    I have seem to fallen in love with sprintf as of late, I find it a much cleaner way of concatenating and outputting variables encoded within strings.

    Does anyone else do this, or is this just a phase I'm going through?

    PHP Code:
    <?php
    $sString 
    'foo';
    echo 
    $sString;
    echo 
    sprintf('Hello %s',$sString);
    ?>
    SilverB.

  5. #5
    Barefoot on the Moon! silver trophy Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,615
    Mentioned
    56 Post(s)
    Tagged
    1 Thread(s)
    Code PHP:
    $foo="bar";
    echo "My name is ".$foo;

    I always use double quotes and always refer to the variable outside the quotes. As far as I know, it's the same basic fail-safe method across PHP, Java, JavaScript, and C#

  6. #6
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Does anyone else do this, or is this just a phase I'm going through?
    Sprintf() was a phase I went though too, but I only stopped because of HereDoc.

    HereDoc makes life much, much easier.
    PHP Code:
    echo <<<FORM
        <form action="{$_SERVER['PHP_SELF']}" method="post" onsubmit="alert('I can use both double and single quotes without needing to escape them. Not a care in the world.');" />
            <select name="mySelect">
                
    {$optionList}
            </select>
            <input type="submit" value="Go go go!" />
    FORM; 
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  7. #7
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I use Single quotes and of course the variables outside of the quotes but until I go for HeareDoc or NewDoc. Single quotes doesn't take compiler to take care of variable interpolation as far as I know.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  8. #8
    ¬.¬ shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    The only problem with HereDoc is it doesn't look very nice with indented code.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  9. #9
    SitePoint Guru
    Join Date
    Dec 2005
    Posts
    982
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    $percent = 99.9;
    echo 'I use single quotes ' . $percent . '% of the time';
    I want to start using Heredoc, but I try not to output large blocks of HTML via php. For large blocks I switch it up a bit and exit out of the parser (this is only for the template layer and never inside of a function):
    Code:
    ?>
    <form action="<?php echo($form['action']); ?>">
    ...
    </form>
    <?php
    MySQL v5.1.58
    PHP v5.3.6

  10. #10
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    The only problem with HereDoc is it doesn't look very nice with indented code.
    What do you mean?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  11. #11
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    The only problem with HereDoc is it doesn't look very nice with indented code.
    What do you mean?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  12. #12
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,094
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by arkinstall View Post
    What do you mean?
    I think he means this:
    HTML Code:
    <div>
      <div>
        <div>
          <div>
            <?php
               print <<<ENDFORM
               <form method="post" action="$form['action']">
    ENDFORM;
    Since ENDFORM has to be at the first character of the line, it kinda screws up the "flow" of the page.
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  13. #13
    ¬.¬ shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Simple simple...
    PHP Code:
    <?php

    class NothingSpecial
    {
        public function 
    nothingHere ()
        {
            
    $var = <<<EOLINE
    ...stuff...
        ...stuff...
        ...stuff...
    ...stuff...
    EOLINE;
            return 
    $var;
        }
    }
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  14. #14
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    It's just one line that is out if you tab the rest:
    PHP Code:
    <?php

    class NothingSpecial
    {
        public function 
    nothingHere ()
        {
            
    $var = <<<EOLINE
                ...stuff...
                    ...stuff...
                    ...stuff...
                ...stuff...
    EOLINE;
            return 
    $var;
        }
    }
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  15. #15
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Yeah, same "problem" with vim - it frigs with the code-folding, well, sometimes.

    Heredoc states the closing tag must be the first char on a line.

    $thing = <<<EOL

    Do stuff.

    EOL;

    In vim, this occasionally causes the code-folder to throw a wobbler, its ok if I close and reopen the file. It doesn't stop me doing using it - its just a PITA.

    I had to refactor some stuff this pm, and now I look at it I am amazed how much I have unconciously adopted the method that BrandonK posted about, I just drop in and out of PHP.

    Read about the alternative PHP syntax too.

  16. #16
    ¬.¬ shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    It's just one line that is out if you tab the rest:
    <snip>
    Only tab the rest if you want those tabs in there. (Not always the case.) Its not really an issue, I just have to look harder while reading the code.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  17. #17
    SitePoint Wizard
    Join Date
    Mar 2008
    Posts
    1,149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I usually put my HTML in separate template files. The PHP files are cleaner, easier to read, easier to scan through, easier to modify later, and easier to write.

    Although when I do need to use variables in strings, I use whatever is appropriate for the project.

  18. #18
    SitePoint Evangelist ferrari_chris's Avatar
    Join Date
    Mar 2008
    Location
    NP, New Zealand
    Posts
    576
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Force Flow View Post
    Code PHP:
    $foo="bar";
    echo "My name is ".$foo;

    I always use double quotes and always refer to the variable outside the quotes. As far as I know, it's the same basic fail-safe method across PHP, Java, JavaScript, and C#
    Put me down for one of these please.

    I use the same method.

  19. #19
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    I always use double quotes and always refer to the variable outside the quotes. As far as I know, it's the same basic fail-safe method across PHP, Java, JavaScript, and C#
    New information. I might change again now.

    Does anyone know offhand how quoting is done in Python? (too busy/lazy to look, atm)

  20. #20
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    In Python, the basic concatenation operator is +. Both quote types can be used (unlike C# and Java) and also, Print has indefinite params so for speed you could use:
    Code python:
    name = 'Rob' + 'ert'
    print 'Hello ', name, '!'

    It also has a similar way of formatting like PHP's sprintf(), which looks like:
    Code python:
    print 'Hello %s!' % (name)
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  21. #21
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Force Flow View Post
    Code PHP:
    $foo="bar";
    echo "My name is ".$foo;

    I always use double quotes and always refer to the variable outside the quotes. As far as I know, it's the same basic fail-safe method across PHP, Java, JavaScript, and C#
    Likewise. I do tend to switch between double and single - I use single for 'simple' text things like constant names in define() etc. Mostly double though, and I never embed variables within it. I don't use heredoc either - I will switch out of PHP instead.

    Anyone using efficiency as a reason is doing it wrong! Readability and maintainability is FAR more important than efficiency/speed. The differences are absolutely minute, and you shouldn't code for efficiency except in the most extreme examples, you will end up making your code look awful / nightmare to maintain.

    Despite several attempts at trying to work it out, I never ever saw the point of sprintf() or why you should use it.

  22. #22
    ¬.¬ shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Stormrider View Post
    Despite several attempts at trying to work it out, I never ever saw the point of sprintf() or why you should use it.
    It is good for ambiguous data into a certain format. For example finding all URLs in a string turning them into html anchors.

    PHP Code:
    <?php

    define
    'ANCHOR_FORMAT''<a href="%s">%s</a>' );

    function 
    convertUrls $m )
    {
        
    $href $m[1]; $title $m[1];
        
    # Do something with $href and $title
        
    return sprintfANCHOR_FORMAT$href$title );
    }

    $s preg_replace_callback'/.../''convertUrls'$s );
    Using sprintf you can change the format without changing the function. This is of course extremely simplified.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  23. #23
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Does anyone know offhand how quoting is done in Python? (too busy/lazy to look, atm)
    Thanks Jake.

  24. #24
    SitePoint Enthusiast stef686's Avatar
    Join Date
    Aug 2005
    Posts
    86
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I prefer single quotes myself, always put my variables outside quotes so singles are faster

  25. #25
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Well, techincally no.

    Logically thinking, creating many single quoted strings would technically be less efficient than one larger double-quoted string with vars in.

    i.e:
    PHP Code:
    $single 'hello my name is '.$name.' and my age is '.$age.'. I live in a '.$building.' in '.$location.'.';
    $double "hello my name is {$name} and my age is {$age}. I live in a {$building} in {$location}."
    5 smaller single quoted strings concatenated with vars, or one double quoted string with vars inside.
    5 creations vs 1. Think about it.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •