Page 115 - Beginning PHP 5.3
P. 115
Chapter 5: Strings
Here ’ s the same example using nowdoc syntax instead:
$religion = ‘Hebrew’;
$myString = < < < ’END_TEXT’
“’I am a $religion,’ he cries - and then - ‘I fear the Lord the God of
Heaven who hath made the sea and the dry land!’”
END_TEXT;
echo “ < pre > $myString < /pre > ”;
The output from this example is as follows (notice how the $religion variable name is not substituted
this time):
“’I am a $religion,’ he cries - and then - ‘I fear the Lord the God of
Heaven who hath made the sea and the dry land!’”
Nowdoc syntax was introduced in PHP 5.3.0.
Other Ways to Create Strings
You don ’ t have to assign a literal string value to create a string variable; you can assign the result of
any expression:
$myString = $yourString;
$myString = “how “ . “are “ . “you?”;
$myString = ( $x > 100 ) ? “Big number” : “Small number”;
In addition, many PHP functions return string values that you can then assign to variables (or display in
the browser). For example, file_get_contents() , which you learn about in Chapter 11 , reads the
contents of a file into a string.
Finding the Length of a String
Once you have a string variable, you can find out its length with the strlen() function. This function
takes a string value as an argument, and returns the number of characters in the string. For example:
$myString = “hello”;
echo strlen( $myString ) . “ < br / > ”; // Displays 5
echo strlen( “goodbye” ) . “ < br / > ”; // Displays 7
strlen() often comes in useful if you want to loop through all the characters in a string, or if you want
to validate a string to make sure it ’ s the correct length. For example, the following code makes sure that
the string variable $year is 4 characters long:
if ( strlen( $year ) != 4 ) {
echo “The year needs to contain 4 characters. Please try again.”;
}
else {
}
// Process the year
}
77
9/21/09 8:53:40 AM
c05.indd 77
c05.indd 77 9/21/09 8:53:40 AM