Get DevWP - WordPress Development Theme

PHP Echo & Print

The way you display or output dynamic text to the browser is with either the Echo or Print Commands/functions. For the most part you will use Echo when outputting text to the browser.

PHP echo Statement Explained

The example below demonstrates how to output text using the echo command.


<?php
  echo "Hello World!" . '<br>';
  echo "Hello" . " World!" . '<br>';
  echo 10 + 8;
?>

As mentioned in the tutorial on PHP Variables, if you want to use variables in your echo statement, you would need to either make sure to nest them in double quotes or concatenate them.

In the example below we use concatenation to effectively output our First, Middle and Last name.


<?php
  $fname = 'John';
  $mname = 'Michael';
  $lname = 'Smith';
  echo $fname . ' ' . $mname . ' ' . $lname;
?>

In the example below we use double quotes to output our First, Middle and Last name.


<?php
  $fname = 'John';
  $mname = 'Michael';
  $lname = 'Smith';
  echo "$fname $mname $lname";
?>

PHP print Statement Explained

The major differences to echo are that print only accepts a single argument and always returns 1. Echo has no return value and can take multiple parameters.

Below we accomplish the same thing we did above by replacing echo with print.


<?php
  $fname = 'John';
  $mname = 'Michael';
  $lname = 'Smith';
  print $fname . ' ' . $mname . ' ' . $lname;
?>

<?php
  $fname = 'John';
  $mname = 'Michael';
  $lname = 'Smith';
  print "$fname $mname $lname";
?>

That’s the gist of how to output or display text with echo and print in PHP.



View Our Themes