php echo

PHP echo command is a means of outputting text to the web browser.

Throughout your PHP career you will be using the echo command more than any other. So let’s give it a solid perusal!

As we saw in the previous examples where we wrote our first program, we used the command echo. This time, we will show the output of a variable that contains a string.

<?php
$dcsText = "techTutorialsOnline.com!";//variable that contains a string
echo $dcsText;
?>

Note we can join two strings i.e a string in a variable and another string. We will learn about this in detail in the upcoming tutorials. See the following code:

<?php
$dcsText = "techTutorialsOnline.com!";//variable that contains a string
echo "Best tutorials website for students and developers : ".$dcsText;
?>

Note: We can also use the HTML tags inside the php echo function for better formatting of our output. To understand this, see the following example:

<?php
$dcsText = "techTutorialsOnline.com!";//variable that contains a string
echo "Best tutorials website for students and developers : <b>".$dcsText."</b>";
?>

 

Careful when echoing quotes!

It is pretty cool that you can output HTML with PHP. However, you must be careful when using HTML code or any other string that includes quotes! Echo uses quotes to define the beginning and end of the string, so you must use one of the following tactics if your string contains quotations:

  • Don’t use quotes inside your string
  • Escape your quotes that are within the string with a backslash. To escape a quote just place a backslash directly before the quotation mark, i.e. “
  • Use single quotes (apostrophes) for quotes inside your string.

See our example below for the right and wrong use of echo:

<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I have an error!</h5>";  

// OK because we escaped the quotes!
echo "<h5 class="specialH5">I have no error!</h5>";  

// OK because we used an apostrophe '
echo "<h5 class='specialH5'>I have no error!</h5>";  
?>

Note:  Echo is not a function; rather it is a language construct.

This is how to use PHP echo command. Raise your question at our Forum Section, if any.