40 views
String Interpolation
To offer developers the maximum flexibility when working with string values, PHP offers a means for both literal and figurative interpretation. For example, consider the following string:
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? 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. These topics are the focus of this section.
Double Quotes
Strings enclosed in double quotes are the most commonly used in most 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 = "Hockey";
echo "My favorite sport is $sport.";
?>
This example returns the following:
My favorite sport is Hockey.
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 within the browser source:
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.
In addition to the newline character, PHP recognizes a number of special escape sequences, all of which are listed in Table 3-14.
Recognized Escape Sequences
————————————–
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
———————————————
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, unless the magic_quotes_gpc configuration directive is enabled. 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.
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 <<<EXCERPT
<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>
EXCERPT;
?>
Several points are worth noting regarding this example:
• The opening and closing identifiers, in the case of this example, EXCERPT, 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, <<<.
• 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 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.
Control Structures
Control structures determine the flow of code within an application, defining execution characteristics such as whether and how many times a particular code statement will execute, as well as when a code block will relinquish execution control. These structures also offer a simple means to introduce entirely new sections of code (via file-inclusion statements) into a currently executing script. In this section you’ll learn about all such control structures available to the PHP language.
Conditional Statements
Conditional statements make it possible for your computer program to respond accordingly to a wide variety of inputs, using logic to discern between various conditions based on input value. This functionality is so basic to the creation of computer software that it shouldn’t come as a surprise that a variety of conditional statements are a staple of all mainstream programming languages, PHP included.
The if Statement
The if statement is one of the most commonplace constructs of any mainstream programming language, offering a convenient means for conditional code execution.
The following is the syntax:
if (expression) {
statement
}
As an example, suppose you want a congratulatory message displayed if the user guesses a predetermined secret number:
<?php
$secretNumber = 453;
if ($_POST['guess'] == $secretNumber) {
echo “<p>Congratulations!</p>”;
}
?>
The hopelessly lazy can forgo the use of brackets when the conditional body consists of only a single statement. Here’s a revision of the previous example:
<?php
$secretNumber = 453;
if ($_POST['guess'] == $secretNumber) echo “<p>Congratulations!</p>”;
?>
The else Statement
The problem with the previous example is that output is only offered for the user who correctly guesses the secret number. All other users are left destitute, completely snubbed for reasons presumably linked to their lack of psychic power. What if you want to provide a tailored response no matter the outcome? To do so you would need a way to handle those not meeting the if conditional requirements, a function handily
offered by way of the else statement. Here’s a revision of the previous example, this time offering a response in both cases:
<?php
$secretNumber = 453;
if ($_POST['guess'] == $secretNumber) {
echo “<p>Congratulations!!</p>”;
} else {
echo “<p>Sorry!</p>”;
}
?>
Like if, the else statement brackets can be skipped if only a single code statement is enclosed.
The elseif Statement
The if-else combination works nicely in an “either-or” situation—that is, a situation in which only two possible outcomes are available. But what if several outcomes are possible? You would need a means for considering each possible outcome, which is accomplished with the elseif statement. Let’s revise the secret-number example again, this time offering a message if the user’s guess is relatively close (within ten) of the secret number:
<?php
$secretNumber = 453;
$_POST['guess'] = 442;
if ($_POST['guess'] == $secretNumber) {
echo “<p>Congratulations!</p>”;
} elseif (abs ($_POST['guess'] - $secretNumber) < 10) {
echo “<p>You’re getting close!</p>”;
} else {
echo “<p>Sorry!</p>”;
}
?>
Like all conditionals, elseif supports the elimination of bracketing when only a single statement is enclosed.
The switch Statement
You can think of the switch statement as a variant of the if-else combination, often used when you need to compare a variable against a large number of values:
<?php
switch($category) {
case “news”:
echo “<p>What’s happening around the world</p>”;
break;
case “weather”:
echo “<p>Your weekly forecast</p>”;
break;
case “sports”:
echo “<p>Latest sports highlights</p>”;
break;
default:
echo “<p>Welcome to my Web site</p>”;
}
?>
Note the presence of the break statement at the conclusion of each case block. If a break statement isn’t present, all subsequent case blocks will execute until a break statement is located. As an illustration of this behavior, let’s assume that the break statements are removed from the preceding example and that $category is set to weather. You’d get the following results:
Your weekly forecast
Latest sports highlights
Welcome to my Web site
Looping Statements
Although varied approaches exist, looping statements are a fixture in every widespread programming language. This isn’t a surprise because looping mechanisms offer a simple means for accomplishing a commonplace task in programming: repeating a sequence of instructions until a specific condition is satisfied. PHP offers several such mechanisms, none of which should come as a surprise if you’re familiar with other programming languages.
The while Statement
The while statement specifies a condition that must be met before execution of its embedded code is terminated. Its syntax is the following:
while (expression) {
statements
}
In the following example, $count is initialized to the value 1. The value of $count is then squared and output. The $count variable is then incremented by 1, and the loop is repeated until the value of $count reaches 5.
<?php
$count = 1;
while ($count < 5) {
printf(”%d squared = %d <br />”, $count, pow($count, 2));
$count++;
}
?>
The output looks like this:
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
Like all other control structures, multiple conditional expressions may also be embedded into the while statement. For instance, the following while block evaluates either until it reaches the end-of-file or until five lines have been read and output:
<?php
$linecount = 1;
$fh = fopen(”sports.txt”,”r”);
while (!feof($fh) && $linecount<=5) {
$line = fgets($fh, 4096);
echo $line. “<br />”;
$linecount++;
}
?>
Given these conditionals, a maximum of five lines will be output from the sports.txt file, regardless of its size.
The do…while Statement
The do…while looping statement is a variant of while but it verifies the loop conditional at the conclusion of the block rather than at the beginning. The following is its syntax:
do {
statements
} while (expression);
Both while and do…while are similar in function. The only real difference is that the code embedded within a while statement possibly could never be executed,
whereas the code embedded within a do…while statement will always execute at least once. Consider the following example:
<?php
$count = 11;
do {
printf(”%d squared = %d <br />”, $count, pow($count, 2));
} while ($count < 10);
?>
The following is the outcome:
11 squared = 121
Despite the fact that 11 is out of bounds of the while conditional, the embedded code will execute once because the conditional is not evaluated until the conclusion.
The for Statement
The for statement offers a somewhat more complex looping mechanism than does while. The following is its syntax:
for (expression1; expression2; expression3) {
statements
}
There are a few rules to keep in mind when using PHP’s for loops:
• The first expression, expression1, is evaluated by default at the first iteration of the loop.
• The second expression, expression2, is evaluated at the beginning of each iteration. This expression determines whether looping will continue.
• The third expression, expression3, is evaluated at the conclusion of each loop.
• Any of the expressions can be empty, their purpose substituted by logic embedded within the for block.
With these rules in mind, consider the following examples, all of which display a partial kilometer/mile equivalency chart:
// Example One
for ($kilometers = 1; $kilometers <= 5; $kilometers++) {
printf(”%d kilometers = %f miles <br />”, $kilometers, $kilometers*0.62140);
}
// Example Two
for ($kilometers = 1; ; $kilometers++) {
if ($kilometers > 5) break;
printf(”%d kilometers = %f miles <br />”, $kilometers, $kilometers*0.62140);
}
// Example Three
$kilometers = 1;
for (;;) {
// if $kilometers > 5 break out of the for loop.
if ($kilometers > 5) break;
printf(”%d kilometers = %f miles <br />”, $kilometers, $kilometers*0.62140);
$kilometers++;
}
The results for all three examples follow:
1 kilometers = 0.6214 miles
2 kilometers = 1.2428 miles
3 kilometers = 1.8642 miles
4 kilometers = 2.4856 miles
5 kilometers = 3.107 miles
The foreach Statement
The foreach looping construct syntax is adept at looping through arrays, pulling each key/value pair from the array until all items have been retrieved or some other internal conditional has been met. Two syntax variations are available, each of which is presented with an example.
The first syntax variant strips each value from the array, moving the pointer closer to the end with each iteration. The following is its syntax:
foreach (array_expr as $value) {
statement
}
Consider this example. Suppose you want to output an array of links:
<?php
$links = array(”www.apress.com”,”www.php.net”,”www.apache.org”);
echo “<b>Online Resources</b>:<br />”;
foreach($links as $link) {
echo “<a href=\”http://$link\”>$link</a><br />”;
}
?>
This would result in the following:
Online Resources:<br />
<a href=”http://www.apress.com”>http://www.apress.com</a><br />
<a href=”http://www.php.net”>http://www.php.net</a><br />
<a href=”http://www.apache.org”> http://www.apache.org </a><br />
The second variation is well-suited for working with both the key and value of an array. The syntax follows:
foreach (array_expr as $key => $value) {
statement
}
Revising the previous example, suppose that the $links array contains both a link and a corresponding link title:
$links = array(”The Apache Web Server” => “www.apache.org”,
“Apress” => “www.apress.com”,
“The PHP Scripting Language” => “www.php.net”);
Each array item consists of both a key and a corresponding value. The foreach statement can easily peel each key/value pair from the array, like this:
echo “<b>Online Resources</b>:<br />”;
foreach($links as $title => $link) {
echo “<a href=\”http://$link\”>$title</a><br />”;
}
The result would be that each link is embedded under its respective title, like this:
Online Resources:<br />
<a href=”http://www.apache.org”>The Apache Web Server </a><br />
<a href=”http://www.apress.com”> Apress </a><br />
<a href=”http://www.php.net”>The PHP Scripting Language </a><br />
There are other variations on this method of key/value retrieval, all of which are introduced in Chapter 5.