PHP Output
Learning how to output data with PHP is really important!
In PHP, there are two output statements.
- echo
And a shorthand syntax for the echo function.
Mostly, we use the echo statement and the shorthand syntax for output. Therefore, we won't be discussing about the print statement.
What is output?
Output is the process that we send a response back to the client. This can be a normal text, HTML markup, XML, Javascript code, or any other kind of text.
PHP Echo Statement
The echo statement can be used to output text, variables, HTML markup, Javascript code, and any other kind of text. Also, echo statement can output values of PHP variables and constants (We already did that in previous examples).
PHP Echo Example - Output Text
<?php
echo "<h1>I love PHP</h1>"; // html markup
echo "I am learning PHP at Hyvor Developer <br>";
echo "PHP: " . "Hypertext Preprocesser" . "<br>"; // connected with concatenation operator
echo "PHP: " , "the best language", " ever"; // connected with multiple parameters
// javascript
echo "<script>alert('Hello');</script>";
Run Example ››echo can output variables.
PHP Echo Example - Output Variables
<?php
$hello = 'Hello World';
echo $hello; // outputs Hello World
echo "<br>";
$x = 5;
$y = 10;
echo $x + $y; // outputs 15
echo "<br>";
$link = 'https://developer.hyvor.com';
echo "<a href=$link>Hyvor Developer</a>";
Run Example ››- echo or echo()
Shorthand Echo
Developers use this shorthand echo syntax when embedding HTML with PHP. Of course, this can be useful in many cases.
This PHP code is a special one in PHP, as it uses a different opening tag. (<?=). Any string output wrapped with <?= and ?> will be echoed. See the following example.
PHP Shorthand Echo Example 2
<?php
$name = 'Hyvor Developer'; ?>
<h1><?= $name ?></h1>
<!-- same as -->
<h1><?php echo $name ?></h1>
<!-- More examples -->
<h2><?= $name . ' Blog' ?></h2>
<h2><?= $name . ' Blog' // comments are allowed ?></h2>
Run Example ››