PHP Programming

From KdjWiki

Jump to: navigation, search

Strings

One of my biggest issues was when to use single quotes (') and when double quotes ("). Here is my explaination and usage justification.

Basically, single quotes are more literal than double quotes. They don't expand variables or control sequences. The only escape character is the slash (\) which can be used to escape single quotes and slashes (see examples below).

The general philosophy I have adopted is as follows:

  • If I want to include a variable or control expansion (such as \n for newline), use double quotes
  • All other times use single quotes

Note: When using variables for expansion, I use the outer bracket syntax:

$str = "this is {$variable} one";
$str = "this is {$obj->variable} one";

General string examples (to illustrate their capabilities):

<?php
  echo 'this is a simple string';

  echo 'You can also have embedded newlines in
    strings this way as it is
    okay to do';

  // Outputs: Arnold once said: "I'll be back"
  echo 'Arnold once said: "I\'ll be back"';

  // Outputs: You deleted C:\*.*?
  echo 'You deleted C:\\*.*?';

  // Outputs: You deleted C:\*.*?
  echo 'You deleted C:\*.*?';

  // Outputs: This will not expand: \n a newline
  echo 'This will not expand: \n a newline';

  // Outputs: Variables do not $expand $either
  echo 'Variables do not $expand $either';
?> 

Double quotes will expand variables and interpret control sequences.

For example:

<?php
  echo "this is a simple string";

  echo "You can also have embedded newlines in
    strings this way as it is
    okay to do";

  // Outputs: Arnold once said: "I'll be back"
  echo "Arnold once said: \"I'll be back\"";

  // Outputs: You deleted C:\*.*?
  echo "You deleted C:\\*.*?";

  // Outputs: You deleted C:\*.*?
  echo "You deleted C:\*.*?";

  // Outputs: This will expand:
  // a newline
  echo "This will expand: \n a newline";

  // Outputs: Variables a b
  $expand = "a";
  $either = "b";
  echo "Variables {$expand} $either";
?>

There is also the Heredoc syntax:

<?php
  $str = <<<EOD
    Example of string
    spanning multiple lines
    including some {$variables}
    and he's able to handle "quoted" words
    using heredoc syntax.
EOD;
?>
Personal tools