PHP - echo and print statements


Advertisements

Previous Page Next Page

There are two ways of displaying output in PHP: using echo and print statement. These two statements are almost same with some minor differences that are listed below.

Difference between echo and print statements

  • echo doesn't return any value while print returns value of 1. Therefore, print can be used in a expression.
  • echo can take multiple parameters separated by comma (,) while print takes only one argument.
  • echo is marginally faster than print.

PHP echo statement

The echo statement can be used with or without parenthesis - echo and echo().

Working with text

The below example illustrates how to use echo statement for displaying text.

<?php
  echo "<h3>This is a HTML line.</h3>\n";
  echo "Single parameter is used with echo statement.\n";
  echo "Multiple ","parameters ", "are used with echo statement.\n";
?>

Output

This is a HTML line.

Single parameter is used with echo statement. Multiple parameters are used with echo statement.

Working with variables

In the below example, echo statement is used to display variables.

<?php
  $x = 15;
  $y = 10;  
  echo "Value of x is ".$x." and Value of y is ".$y.".\n";
  //another way to display the same
  echo "Value of x is $x and Value of y is $y.\n";
?>

Output

Value of x is 15 and Value of y is 10.
Value of x is 15 and Value of y is 10.

PHP print statement

The print statement can also be used with or without parenthesis - print and print().

Working with text

The below example illustrates how to use print statement for displaying text.

<?php
  print "<h3>This is a HTML line.</h3>\n";
  print "Only single parameter can be used with print statement.\n";
?>

Output

This is a HTML line.

Only single parameter can be used with print statement.

Working with variables

In the below example, print statement is used to display variables.

<?php
  $x = 15;
  $y = 10;  
  print "Value of x is ".$x." and Value of y is ".$y.".\n";
  //another way to display the same
  print "Value of x is $x and Value of y is $y.\n";
?>

Output

Value of x is 15 and Value of y is 10.
Value of x is 15 and Value of y is 10.

Previous Page Next Page
Advertisements