Strings

☰ Menu Content


Throughout your PHP career you will be using strings a great deal.

Therefore having a basic understanding of PHP strings is very important

String Creation

A string can be used directly in a function or it can be stored in a variable.

In the two examples below, the same string was created twice:

First Example -- The string was stored in a variable and then echoed.

PHP Code:
<?php

$my_string="PhpMyanmar.com-Unlock your potential!";
echo $my_string;

?>

Display:
PhpMyanmar.com - Unlock your potential!

Second Example -- The string was directly echoed.

PHP Code:
<?php

echo "PhpMyanmar.com-Unlock your potential!";

?>

Display:
PhpMyanmar.com - Unlock your potential!

String Creation Single Quotes

We have created strings using double-quotes up to now,? but it is just as correct to create a string using single-quotes, (apostrophes).

PHP Code:
<?php

$my_string = 'PhpMyanmar.com - Unlock your potential!';
echo 'PhpMyanmar.com - Unlock your potential!';
echo $my_string;

?>

If you want to use a single-quote within the string you have to escape the single-quote with a backslash \ . Like this: \' !

PHP Code:
<?php

echo 'PhpMyanmar.com - It\'s super';

?>


String Creation Double-Quotes

Double-quotes should be used as?the primary method for forming strings.

Double-quotes allows many special escaped characters to be used that you cannot do with a single-quote string.

See below where backslashes are used to escape a character.

PHP Code:
<?php

$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";

?>

Escaped characters shown above are not very useful for outputting to a web page because HTML ignore extra white space( tab, newline, and carriage return are all examples of extra 'ignorable' white space)

But when writing to a file that may be read by human eyes these escaped characters are a valuable tool!

String Creation Heredoc

PHP has a very robust string creation tool called heredoc?

It lets the programmer create multi-line strings without using quotations.

PHP Code:
<?php

$my_test_string = <<<MYTEST
PhpMyanmar.com,
Php Tutorials,
Try it.
MYTEST;

echo $my_test_string;

?>

Few very important things to follow when using heredoc.

  • Use <<< and some identifier that you choose to begin the heredoc. In this example we chose MYTEST as our identifier.
  • Repeat the identifier followed by a semicolon to end the heredoc string creation. In this example that was MYTEST;
  • The closing sequence MyTEST; must occur on a line by itself and cannot be indented!
Display:
PhpMyanmar.com, Php Tutorials, Try it.

Note
For more detail please see Php Manual at http://www.php.net

Php Tutorial Content (menu)