PHP echo() Function
echo() function outputs one or more strings.
The following table summarizes the technical details of this function.
|Return Value:||No value is returned.|
The basic syntax of the
echo() function is given with:
The following example shows the
echo() function in action.
<?php echo "Hello World!"; ?>
echo is not actually a function, it is a language construct (like if statement), so you can use it without parentheses. Also,
echo is considered marginally faster than the
echo() function accepts the following parameters.
|strings||Required. One or more strings to be sent to the output.|
Here're some more examples showing how
echo() function actually works:
The following example shows how to print multiple strings at once using concatenation operator.
<?php // Defining variable $str1 = "Hi There"; $str2 = "Have a nice day"; // Printing variables values echo $str1 . "! " . $str2 . " :)"; // Above statement can also be written as echo "$str1! $str2 :)"; ?>
You can also print variable value as well as HTML tags using the echo statement, like this:
<?php // Defining variable $age = 18; // Printing variable value echo "<h1>Your age is $age.</h1>"; ?>
If you use single quote (
'), variable will be displayed literally instead of value, as shown here:
<?php // Defining variable $color = "blue"; echo "Sky is $color"; // Prints: Sky is blue echo 'Sky is $color'; // Prints: Sky is $color ?>
echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign, to quickly print variable value inside HTML, as shown below:
<?php // Defining variable $name = "John"; ?> <!--Printing variable value inside HTML--> <p>Hi, <?= $name ?>. Good to see you.</p>