PHP - Echo content

  »   PHP Introduction  »   PHP Tutorial - Echo/Print content

PHP has basically two ways of sending content to the browser and those are echo and print. The difference is that print returns a value of 1 when execute while echo doesn't return anything. Another difference is that em>print accepts only one argument while echo accepts a list of arguments (as many as you like). In PHP we normally use echo to output content while print it left aside for rare and very specific situations.

Echo can be both used with or without parenthesis: echo and echo() are equivalents. According to the PHP manual "echo is not actually a function, it is a language construct"

PHP<?php 
$a = "Hello";
$b = "John Doe";
$x = 1;
$y = 2;

echo "Hello World"; // echoes Hello World
echo "$a $b"; 	// echoes Hello John Doe
echo $a.' '.$b.', how are you today?'; // echoes Hello John Doe, how are you today?
echo $x + $y; // echoes 3
?>

Using single o double quotes when echoing

Did you note the quotation mark used to echo? We used both double quotes and single quotes. The difference is that single quotes will print the variable name, and double quotes will print the value

PHP<?php 
$no = "12";

echo "Lucky number $no <br/>"; // echoes Lucky number 12
echo 'Lucky number $no'; // echoes Lucky number $no
?>

Shorthand echo - Write code faster

Echo has a syntax shortcut so you can easily insert it into your HTML content.

PHP<?php 
$no = "12";
?>

<p>Lucky number <?=$no?></p>

Before PHP 5.4.0, You will need to have the short_open_tag enabled in order to work

The PHP print function

Similar to echo, the print function can be used both with parenthesis or without them.

PHP<?php 
$a = "Hello";
$b = "John Doe";
$c = "World";

print($c); // prints Hello World
print "$a $b"; 	// prints Hello John Doe
print $a.' '.$b.', how are you today?'; // prints Hello John Doe, how are you today?
?>

Go ahead and practice a little bit with the PHP echo statement. This is one of the fundamental functions when you start working with PHP. It allows you to build dynamic expressions that will adapt to different situations.