Searching...
Thursday 20 June 2013

PHP Basics–Part 7 :: String Interpolation


When you need to control which php [more about php scripting language] code should be parsed and which should not or you want to beautify your code blocks, you'll be needing these string interpretation means. These will provide you with complete flexibility when working with string values. PHP offers a means for both literal and figurative interpretation. For instance take this example:-

The $animal jumped over the wall.\n

You might assume that $animal is a variable and that \n is a newline character, and therefore both should be interpreted accordingly. However, what if you want to output the string exactly as it is written, or perhaps you want the newline to be rendered but want the variable to display in its literal form($animal), or vice versa? ..Things got complicated here!! No, not really!! All of these variations are possible in PHP, depending on how the strings are enclosed and whether certain key characters are escaped through a predefined sequence. I'll help you over it..

Double Quotes

Strings enclosed in double quotes are the most commonly used in PHP scripts because they offer the most flexibility. This is because both variables and escape sequences will be parsed accordingly. Consider the following example:

<?php
$sport = "boxing";
echo "Jason's favorite sport is $sport.";
?>

This example returns the following:

Jason's favorite sport is boxing.

Escape Sequences

In addition to the newline character, PHP recognizes a number of special escape sequences, all of which are listed in Table below.

Sequence Description
\n Newline character
\r Carriage return
\t Horizontal tab
\\ Backslash
\$ Dollar Sign
\” Double quote
\[0-7]{1,3} Octal Notation
\x[0-9A-Fa-f]{1,2} Hexadecimal Notation
Escape sequences

Escape sequences are also parsed. Consider this example:

<?php
$output = "This is one line.\nAnd this is another line.";
echo $output;
?>

This returns the following (as viewed from within the browser source.. point to be noted!!):

This is one line.
And this is another line.

It’s worth reiterating that this output is found in the browser source rather than in the browser window. Newline characters of this fashion are ignored by the browser window. However, if you view the source, you’ll see that the output in fact appears on two separate lines. The same idea holds true if the data were output to a text file. (Outputting data to the browser in php)
So all i am saying is that the output above will be in the page source and not in the browser's output window. You must be asking yourself what is the use of this if we won't get output in the browser window. Take this example for now:-

<?php
$link= 'http://www.google.com';
echo "<a href=\"$link\">Google</a>";
?>

Output in browser source:

<a href="http://www.google.com">Google</a>

Output in browser window:


I guess this example must have cleared your doubts. Now moving on to single quotes.

Single Quotes

Enclosing a string within single quotes is useful when the string should be interpreted exactly as stated. This means that both variables and escape sequences will not be interpreted when the string is parsed. For example, consider the following single-quoted string:

print 'This string will $print exactly as it\'s \n declared.';

This produces the following:

This string will $print exactly as it's \n declared.

Note:- that the single quote located in it's was escaped. Omitting the backslash escape character will result in a syntax error.

Consider another example:

print 'This is another string.\\';

This produces the following:

This is another string.\

In this example, the backslash appearing at the conclusion of the string has to be escaped; otherwise, the PHP parser would understand that the trailing single quote was to be escaped. However, if the backslash were to appear anywhere else within the string, there would be no need to escape it.

print 'This is \another string.';

This produces the following:

This is \another string.


Curly Braces

While PHP is perfectly capable of interpolating variables representing scalar data types, you’ll find that variables representing complex/compound data types such as arrays or objects cannot be so easily parsed when embedded in an echo() or print() string. You can solve this issue by delimiting the variable in curly braces{}, like this:

echo "The capital of Ohio is {$capitals['ohio']}.";

Personally, I prefer this syntax, as it leaves no doubt as to which parts of the string are static and which are dynamic. And in php there is no place for mistakes... lol but i am serious.

Heredoc

Heredoc syntax offers a convenient means for outputting large amounts of text. Rather than delimiting strings with double or single quotes, two identical identifiers are employed. An example follows:

<?php
$website = "http://www.romatermini.it";
echo <<<HOMEY
<p>Rome's central train station, known as <a href = "$website">Roma Termini</a>,
was built in 1867. Because it had fallen into severe disrepair in the late 20th
century, the government knew that considerable resources were required to
rehabilitate the station prior to the 50-year <i>Giubileo</i>.</p>
HOMEY;
?>

Several points are worth noting regarding this example:
  • The opening and closing identifiers (in the case of this example, HOMEY) must be identical. You can choose any identifier you please, but they must exactly match.
    The only constraint is that the identifier must consist of solely alphanumeric characters and underscores and must not begin with a digit or an underscore.
  • The opening identifier must be preceded with three left-angle brackets (<<<). I repeat three left-angle brackets.
  • Heredoc syntax follows the same parsing rules as strings enclosed in double quotes. That is, both variables and escape sequences are parsed. The only difference is that in heredoc double quotes do not need to be escaped.
  • The closing identifier must begin at the very beginning of a line. It cannot be preceded with spaces or any other extraneous character. This is a commonly recurring point of confusion among users, so take special care to make sure your heredoc string conforms to this annoying requirement. Furthermore, the presence of any spaces following the opening or closing identifier will produce a syntax error.
Heredoc syntax is particularly useful when you need to manipulate a substantial amount of material but do not want to put up with the hassle of escaping quotes. Try it, you won't regret.

Nowdoc

Introduced in PHP 5.3, nowdoc syntax operates identically to heredoc syntax, except that none of the text delimited(escaped) within a nowdoc is parsed. If you would like to display, for instance, a snippet of code in the browser, you could embed it within a nowdoc statement; when subsequently outputting the nowdoc variable, you can be sure that PHP will not attempt to interpolate any of the string as code.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'HOMEY'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

<<<'HOMEY' Stuffed_data_goes_here
Homey;

To be clear as double quotes is to single quotes -> heredoc is to nowdoc
You should start your journey to php with PHP BASICS

2 comments:

  1. You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting
    for your next post keep on updating these kinds of knowledgeable things...
    PHP training in chennai

    ReplyDelete
  2. This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
    Texting API
    Text message marketing
    Digital Mobile Marketing
    Mobile Marketing Services
    Mobile marketing companies
    Fitness SMS

    ReplyDelete

 
Back to top!