This tutorial shows how to handle strings in PHP, different output methods, functions and the significance of using each of them. A string can be literally expressed in the following ways in PHP
1. Single Quoted
2. Double Quoted
3. HEREDOC
4. NOWDOC (from ver. PHP 5.3.0)
Different methods used to handle strings are:
1. Print
2. Echo
3. Sprintf
4. Print_r
5. Var_dump
Single Quoted String:
The simplest way to specify a string is to enclose it in single quotes (the character ‘). To specify a single quote in your string you will need to escape it with a back slash (). In single quotes all special Characters are not recognised unless they are escaped with the back slash ().
Examples
<?php
echo (‘I’m a PHP programmer’);
echo ('<br>');
echo (‘This is the way to output a back slash and forward slash /');
?>
Single Quotes treats Variables as its face value and does not recognise the special characters unless escaped.
Double Quoted String:
Double quoted string is one of the most common method used to specify a string. It has its own advantages and disadvantages. Double quoted string treat variables by expanding it with its value and it also recognizes all the special characters.
<?php
echo ""I’m a PHP programmer"";
echo "This is the way to output a back slash and forward slash /”
?>
HEREDOC:
Third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Syntax:
<?php
$variable = <<<EOT
String CONTENT
EOT;
echo <<<EOT
My name is "$name". I am printing some $var->object.
Now, I am printing some {$var->object[1]}.
This should print a capital 'A': x41
EOT;
?>
HEREDOC method can be used whenever you have a lot of HTML to be displayed. It can recognise variables and special characters like the double quoted string.
In the above example EOT can be replaced with any value unless you follow the naming rules. Examples: HMV, ROCK, WEBY
NOWDOC:
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.
A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<‘EOT’. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.
Syntax:
<?php
$variable = <<<’EOT’
String CONTENT
EOT;
echo <<<’EOT’<br />
My name is "$name". I am printing some $var->object.
Now, I am printing some {$var->object[1]}.
This should print a capital 'A': x41
EOT;
?>
String Functions:
print()
print function outputs a string
Example:
int print (string $arg)
print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.
Various Method of Using print:
<?php
print("Hello World");
print "print() also works without parentheses.";
print "This spans
multiple lines. The newlines will be
output as well";
print "This spans multiple lines. The newlines will be n output as well.";
print "escaping characters is done "Like this".";
print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END; //(USING HEREDOC)
print $foo; //(Printing Variables)
?>
echo
echo — Output one or more strings
Example:
void echo ( string $arg1 $arg2 );
Outputs all parameters.
echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.
Various Method of Using echo:
<?php
echo "Hello World";
echo "This spans
multiple lines. The newlines will be
output as well";
echo "This spans multiple lines. The newlines will be n output as well.";
echo "Escaping characters is done "Like this".";
echo $foo;
echo $foo,$bar;
echo <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
END;
echo $some_var ? 'true': 'false';
?>
sprintf
sprintf returns a string produced according to the formatting string format. Type Specifier that says what type the argument data should be treated as. The conversion specifiers are useful to format or transform the values. Each conversion specifier starts with a single percent symbol%) and ends with a conversion character (one ofb, c,d,f,o,s, u,x, orX ). Please refer http://in2.php.net/manual/en/function.sprintf.php for complete list of specifiers along with descriptions.
Example
<?php
$str = "Hello";
$number = 123;
$txt = sprintf("%s world. Day number %u",$str,$number);
echo $txt;
?>
Output
Hello world. Day number 123
print_r:
Prints human-readable information about a variable
print_r (mixed $expression [, bool $return])
print_r() displays information about a variable in a way that’s readable by humans. print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown. Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning. Main practical use of print_r() function is to output array values.
Example:
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
Output:
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)
var_dump:
Var_dump is used to get information about a variable. This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure. In PHP 5 all public, private and protected properties of objects will be returned in the output.
Example:
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>
Output:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
The echo and print functions are similar is all aspects. The only difference between them is that when items are separated using a comma, the echo function performs faster.