Saturday, 14 May 2011

PHP STRINGS - SINGLE QUOTED PHP STRINGS





The simplest form of PHP strings is the single quoted PHP string; it consists in putting the chain of characters constituting your string between single quotes (for instance, consider the PHP string $s = 'understanding').


The particularities of single quoted PHP strings are the following:
  • if you intend to have a literal single quote in your chain of characters, you need to escape it with a backlash \ in order to prevent it from being mistaken with the single quote which terminates the string.

    Learn the PHP code:
    <?php
    $s = 'Here\'s how you do it';
    echo $s;
    ?>

    Run the PHP script in your web browser:

    Escaping single quotes in php strings
  • likewise, if you intend to have a backlash followed by a single quote within your chain of characters, you need to double the backlash, etc ...

    Learn the PHP code:
    <?php
    $s = 'String terminating with (one) backlash \\';
    echo $s;
    ?>


    Run the PHP script in your web browser:

    Double backlash in PHP strings
  • if you intend to terminate your chain of characters with a backlash, you need to double it.
  • PHP variables within single quoted strings are not parsed.

    Learn the PHP code:
    <?php
    $var = 1;
    $s = 'The variable $var will not be parsed';
    echo $s;
    ?>


    Run the PHP script in your web browser:

    PHP variable not parsed in single quoted string

    PHP STRINGS - DOUBLE QUOTED PHP STRINGS

    The essential difference between a single quoted PHP string and a double quoted PHP string lies in the fact that a PHP variable will be parsed in the latter and won't be parsed in the former.
    Learn the PHP code:
    <?php
    $var = 1;
    $s = "The variable $var will now be parsed";
    echo $s;
    ?>
    Run the PHP script in your web browser:
    php variable parsed in double quoted string

No comments:

Post a Comment