PHP print Statement

The PHP print statement is used to output some data on the screen or on the web. For example:

<?php
   print "PHP is Fun!";
?>

The output of above PHP example, is:

php print

The same (previous) example can also be created in this way:

<?php
   $x = "PHP is Fun!";
   print $x;
?>

Let me create the same example in another way:

<?php
   $x = "PHP is Fun!";
   print($x);
?>

It produces exactly same output as of previous example, because ($x) evaluated as ("PHP is Fun!"), which is a valid expression.

Note - But let me tell you one thing that use parentheses only when you need to give priority for an expression to be executed first. For example:

<?php
   print(1+3) * 12;
?>

The output of above PHP example, is:

php print statement

In above example, if you will remove the parentheses, then the output should be 37. This is the situation where we need to use parentheses. Otherwise, print does not requires any parentheses to output the data on screen.

PHP print Statement Example

<?php
   $x = 24;
   print $x;
   print "<hr>";
   
   $x = 18.93;
   print $x;
   print "<hr>";
   
   $x = "Hey!";
   print $x;
   print "<hr>";
   
   $x = "Hey,<br>is everything OK?";
   print $x;
?>

The output of above PHP example, is:

php print example

Note - Use echo instead of print to output data on the screen. But since the print statement always returns 1, therefore use print when needed to execute as a expression. For example:

<?php
   $x = '';
   print print $x;
?>

This example will produce 1. Let me create another example based on this scenario:

<?php
   $x = 'hello';
   print print $x;
?>

The output of above PHP example, is:

print php

Now the time is to create one last example on print statement or keyword to complete the tutorial on it:

<?php
   if(print "codes")
   {
      echo "cracker";
   }
?>

The output of above PHP example, is:

print statement example php

PHP Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube