PHP Echo in PHP

by Hiroshi on June 19, 2008

in Concatenation, Echo, PHP Basics

PHP function echo is a means of outputting text to the web browser. Here is how we can use echo in PHP in different ways.

<?php
echo "Hello World";
?>

With HTML Tags

<?php
echo "<font color='#000000'>Hello World</font>";
?>
<font color="green">
<?php
echo "Hello World";
?>
</font>

Encoding Quotes – Escaping And Use of Apostrophe

You can output HTML with PHP. However, you must be careful when using HTML code or any other string that includes quotes! The echo function 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
<?php
// This won't work because of the quotes around special H1.
echo "<h1 class="someclass">Hello World!</h1>";
 
// OK because we escaped the quotes!
echo "<h1 class=\"someclass\">Hello World!</h1>";
 
// OK because we used an apostrophe '
echo "<h1 class='someclass'>Hello World!</h1>";
?>

Echoing Variables

No quotations are required while echoing variables, even if the variable does not hold a string. Below is the correct format for echoing a variable.

<?php
$string = "Hello World.  My name is: ";
$number = 4;
$letter = a;
echo $string;
echo $number;
echo $letter;
?>

Echoing Variables and Text Strings

Variables and text strings are joined together with a period( . ). The example below shows how to do such a combination.

<?php
$string = "Hello World.  My name is: ";
$newline = "<br />";
echo $string."Bobettta".$newline;
echo "Hi, I'm micky.  Who are you? ".$string.$newline;
echo "Hi, I'm micky.  Who are you? ".$string."Bobetta";
?>

Related Posts

Previous post:

Next post: