Printing Strings in PHP
In this section, we will learn to print strings. Also, see how to print values of variables along with strings, with help of some examples.
A simple printing example
Simple printing in PHP means that we will assign a string to a variable and print its value in the output. Let us begin with this simple example.
<?php echo "This is a string"; //Output- This is a string echo "String in multiple lines also work"; //Output- String in multiple lines also work echo "Let's rock"; //writing the above using single quote //will not work without a escape character //in this case it is a backslash \ echo 'Let\'s Rock'; //Try the above without a \ and see the difference! echo 'First line \n Second line'; //will not work - single quote echo "New line \n second line"; //will work - double quotes ?>
In the above example, we used a backslash when we enclosed the string 'Let's Rock' in single quote. This is called escaping. This is essential when you want to avoid PHP from processing certain portion of code. For example, if you can put \ in front of variable $string in your echo statements to avoid printing the value of the variable, such as \$string. Sometimes, you may have to put more backslashes, like \\\$string.
Printing Variables in PHP
We will now look at assigning a string to a variable and printing its value as an output using the variable itself. See this example:
<?php
$string = '100 pages'; //Assigning a string to a variable
echo 'I want to print $string';
//Output: I want to print $string
echo "I want to print $string";
//Output: I want to print 100 pages
echo "I will print $string's";
//this will work as a variable name can not have
//the ' character!
echo "I will print $strings";
//will not work, it will look for a variable name $variables
echo "I will print {$string}";
//will work, {} are not considered as part of variable names
echo "I will print ${string}";
//will work, {} are not considered as part of variable names
?>
You must try to experiment with the above code and modify it to see how it works. That will be a great learning experiencing for you.
Let's also take a look at some built-in constructs of PHP that we can make use of to print one or more strings. Some of these are:
- print and
- printf
These built-in constructs can be used in the same way we use 'echo' to print strings.
We will now move on to our next tutorial on comparing strings in PHP.