Articles in Basics Category

Printing Content with echo()

If you want to add anything from your PHP script to the output PHP engine generates (which then would be sent to the client), you can use echo() language construct for that.


if (date('G') < 12) {
    $greeting = 'Good Morning!';
} else {
    $greeting = 'Welcome!';

echo $greeting;


Copy above code and run it as greeting.php. You would see either Good Morning or Welcome depending on current time (date() function uses server’s time and it may be different from your PC’s time). Now just comment out echo statement like below and re-run the file.

//echo $greeting;

You would see nothing. So, if you want anything to be added to the output, you should use echo() for that.

Different Usage of echo()

echo $greeting;
echo ($greeting);

Both statements above produce same output. You can use echo() with or without brackets because it’s a language construct and not a function. You would usually see echo() without brackets.

$myAge = 10;
echo 'My age is '.$myAge;
echo "My age is $myAge";

In two statements above, first one uses string concatenation while second one includes the variable within double quotes. Refer Usage of Quotes for more explanation on using variables inside quotes.

$intro = 'My age is ';
$myAge = 10;

echo $intro, $myAge;

Above statement would output My age is 10. This is an example to show that echo() (without brackets) can take more than one argument. However this way of usage is bit uncommon. Instead you would usually see string concatenation or variables within double quotes when it’s required to output more than one variable using a single echo() statement.

Difference Between echo() and print()

print() is also a language construct and behaves almost same as echo(). Noticeable differences are print() can’t take more than one argument and print() has a return value which is always 1.

Where to Head from Here...
Share with Your Peers...

We Value Your Feedback...

We love to hear what you think about this article. Please provide your opinion, suggestions and improvements using following form. Note that submitted feedback is not displayed but we will get back to you if it needs a reply.