Quick Reach
The print statement of PHP
The Print statement or command in PHP is used to display the output of a given variable or expression.
See an example of print statement
The PHP print statement can display the output of any type of data.
The print Syntax
Following is the syntax of the print statement:
print <expression>;
An example of print statement
In this example, a string and a variable are displayed by using the print statement.
1
2
|
print “My code is working”;
print $variable_name;
|
Example 2:
1
2
3
4
5
6
7
8
|
<?php
Print “Hello”;
//Outputs a string
Print $variable;
//Outputs a variable
Print “String with variables “ . $on . ” one line”;
//Outputs a string, then a variable, then a string. All are separated with a [.] period
?>
|
Single line print statement
1
|
print “This is single line print statement”;
|
Multi-line PHP print statement
Following is an example of the multi-line single print statement:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?
# First Example
$variable = “test vairable”;
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;
# Second Example
print “This spans
multiple lines. The newlines will be
output as well”;
?>
|
Be careful when printing quotes!
Follow these guidelines to use quotes as using the print statement to display strings.
- Use a backslash () within the strings to escape your quotes. Before the quotation mark just place a backslash.
- Inside your strings, use single quotes (‘ ‘)
See examples below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php
// This is wrong approach and produces an error
print “<h1 class=”headerh1“>I love using PHP!</h1>”;
/* The compiler takes first 2 quotes “<h5 class=” as a complete print statement
while start interpreting following code as php’s and not able to identify it
*/
// Escaping the code
print “<h1 class=”headerh1“>I love using PHP!</h1>”;
// Using apostrophe
print “<h1 class=”headerh1“>I love using PHP!</h1>”;
?>
|
Print PHP Variables
Printing a variable is simple in PHP. It simply requires writing the print statement which is followed by a variable name. See examples below:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?php
$my_name = “Hello Mike. My name is: “;
$my_no = 4;
$my_letter = a;
print $my_name;
print $my_no;
print $my_letter;
?>
|
Output is : Hello Mike. My name is: 4a
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
|
<?php
$inta = 10;
$intb = 20;
$intc = $inta + $intb;
print $intc;
?>
|
Output is : 30
Useful Reading: PHP printf function | PHP print_r function
Leave A Comment?