Using echo

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

As we used in previous pages, the PHP command echo is a way to uotput text to the web browser. Echo is the most commonly, and most ofetenly used command while working in PHP

We use echo to output a string. You can either use a variable or the string itself within quotes.

For eg:

<?php
$myString = “PHP”;
echo $myString;
echo “<h5>PHP is too good!</h5>”;
?>

Output:

PHP
PHP is too good!

The text that we output through echo is sent to the user in the form of a web page. So we can also use HTML tags inside the echo command,

Careful When Echoing Quotes!

It seems very good to be able to output HTML with PHP. However, you must be careful when using HTML code, when it contains quotes. Echo uses quotes to mark the beginning and end of the string, so you must not use quotes other than at the starting and the ending. If its necessary to use quotes inside echo you must use one of these methods

Use escape sequence to escape your quotes from echo ie just put a backslash directly before the quotation mark, like \”

Use single quotes (apostrophes) for quotes inside your string like ‘ ’.

<?php
Echo “<h5 class=”specialH5”>I Love PHP!</h5> //doesn’t work
echo “<h5 class=\”specialH5\”>I love using PHP!</h5>”; //works
?>

Echoing Variables

While echoing variables in PHP no quotations are required. They are written directly with echo as:

For eg:

<?php
$my_string = “PHP is too good  ”;
$my_number = 4;
$my_letter = U;
echo $my_string;
echo $my_number;
echo $my_letter;
?>

Output:

PHP is too good 4U

Echoing Variables and Text Strings

You can also place variables inside of double-quoted strings. This tells the PHP interpreter to output the string value of the variable to be printed in the place of the variable.

For eg:

<?php
$my_string = “PHP is too good”;
echo “$my_string to use <br />”;
echo “PHP is a scripting language $my_string <br />”;
echo “PHP is a scripting language $my_string to use”;
?>

Output:

PHP is too good to use
PHP is a scripting language PHP is too good
PHP is a scripting language PHP is too good to use

Using variables saves time and provide reusability, you don’t need to retype the whole string over and again whenever you want to use it. With variables you can just use the variable whrever theres a need to use the same variable. It makes the code readable.

You should always use double quotes with string variables, as single quotes will not give the value of the string rather it will just print the variable name like

$my_string

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.