PHP echo to print HTML, New Line, Text and Array

by Vincy. Last modified on June 23rd, 2022.

PHP echo is a one of the widely used statements. PHP language has the print() function also. It outputs the same as what the echo statement does.

If you are in an urge, the quick example below will save your time. It uses PHP echo to print various types of data, formats. It prints,

  1. a string, boolean
  2. string with variable interpolation
  3. result of an expression
  4. HTML

Quick Example

<?php 
//To print a string
echo "Hello world!";

//To print interpolated string
$functionName = "PHP echo()";
echo "Print statement - " . $functionName;


//To print Boolean
$boolean = true;
echo "Boolean true: " . $boolean;
?>

Prints the result of an expression ($a * $a) – $a

<?php 
$a = 5;
echo '$result  = ' . (($a * $a) - $a);
?>

Prints HTML table

<?php 
echo '<table class="html-table">
        <tr>
            <th>Print statements</th>
        </tr>
        <tr>
            <td>echo</td>
        </tr>
        </table>';
?>

php echo quick example

This article covers the maximum on the PHP echo statement. It contains numerous examples using this echo() construct. The highlights are,

  1. It differentiates echo with single vs double-quotes.
  2. It creates custom echo functions to make the data safe to print.
  3. It handles escape sequences on printing.

We have already seen about PHP print statement in PHP. The linked article has short notes on each print statement.

PHP Echo

Basics about PHP echo

Before start coding with the PHP echo() statement, let us see a basic knowledge about it. This section covers PHP echo with the following list of items.

  1. Overview
  2. Syntax and parameters
  3. Usage practices

Overview

The echo is not a function but a language construct in PHP. Generally, the language constructs return values. But the PHP echo is not.

It accepts one or more string expressions to print. It returns void.

Note:

The main difference between the PHP echo() and print() are,

  1. Return value: PHP print() returns 1 always.
  2. Parameters: PHP print() receives single parameter unlike echo().
  3. echo() is slightly faster than print()when using more strings in a single statement.

Syntax and parameters

The following syntax is for using a PHP echo statement.

echo(string ...$expressions)

expressions – to receive one or more strings to output. All are separated by comma to print without space or line breaks.

Usage practices

There is no need to add parathesis to the PHP echo statement. But, the PHP allows executing the echo statement with parenthesis also.

There is also a short-form of using PHP echo statement. The syntax is shown below. Before using this form ensure that the php.ini config has short_open_tag enabled.

<?=$var;?>

More examples on PHP echo

Echo one or more comma-separated-string

We can print one or more strings using any one of the below methods.

  • By specifying the comma-separated values on the PHP echo statement.
  • By adding concatenated strings on the PHP print/echo statement.

The below example uses the first way of putting strings together in a sequence.

examples/echo-comma-separated-strings.php

<?php
echo "echo ", "printing ", "multiple ", "string";
?>

Echo statement with escape sequences

This example displays how the PHP echo statement handles the escape sequences.

It uses escape sequences \n in the echo statement which prints a new line. The new line will not be significant unless you view the page source. This example code uses <PRE> tags to make it visible in the output.

Within double-quotes, the string starts with $ will be parsed as a variable. This example escapes the $ symbol by using a backslash before it.

examples/echo-with-escape-sequence.php

<?php
$string = 'Learn PHP Echo';
print "<PRE>";
echo "Hello World! \$string\n\n";
echo "PHP echo prints the value in the variable \"str\": $string\n\n";
echo "Hello\nWorld!\nLearnPHP\n\n";
?>

echo with escape sequence

Echo statement with single vs double quotes

The below code shows the difference between single and double quotes in PHP echo.

The echo statement parses the $string variable interpolated with string values. But, the statement with single quotes does not parse. The output shows the difference

Using single quotes

<?php
$string = "Value of a variable";
echo 'Hello World! $string';
?>

Using double quotes

<?php
echo "Hello World! $string";
?>

echo with single double quotes

Echo multi-line text entered by the user

This example will show a textarea to the user to enter a multi-line text. The form submit action will call PHP to process the text entered and print it to the browser. The PHP echo statement parses the breaks at the end of the line and prints a multi-line text.

examples/print-multi-line.php

<form action="" method="post">
	<h2>Print multi-line passage</h2>
	<div class="row">
		<label>Enter a multi-line text:</label>
		<div>
			<textarea class="textarea" name="multi-line" rows="5"></textarea>
		</div>
	</div>
	<div class="row">
		<input type="submit" value="Submit" name="submit" class="btn-submit">
	</div>
</form>

<?php
if (! empty($_POST["submit"])) {
    if (! empty($_POST["multi-line"])) {
        $string = $_POST["multi-line"];
        echo "Output:";
        echo "<PRE>";
        echo $string;
    }
}
?>

Printing array using PHP functions

Echo array element

It shows how to print a single array element using PHP echo(). It prints the first element of the input array assigned in the below code.

<?php
$color = array(
    "Red",
    "Blue",
    "Green"
);
echo "First Element: " . $color[0];

Echo object array property

This program includes a property array in the form of JSON. It shows code how the print a property value of an object array.

<?php
$userDetailsArray = '{"name":"Kevin","age":13}';
$userDetails = json_decode($userDetailsArray);
print "<pre>";
echo "Name: " . $userDetails->name;
echo "\nAge: " . $userDetails->age;
print "</pre>";
?>

Using print_r()

It prints the complete array in a tree structure. The PHP function print_r() is used to print the whole array.

<?php
$color = array("Red", "Blue", "Green");
print "<pre>";
print_r($color);
print "</pre>";
?>

Using var_dump()

The var_dump() function is to print the array with meta. The metadata specifies the array element type, length and more.

<?php
print "<pre>";
var_dump($color);
print "</pre>";
?>

How to make data safe to echo

This is very useful code that makes PHP echo with safe data. It applies PHP htmlspecialchars() function to get rid of vulnerable scripts to print.

It uses Phppot vendor class Util() which has the safe echo utilities. These utilities use different combinations of flags to set encoding.

The below code prevents parsing HTML5 canvas. It converts the special characters into HTML entities. It is to prevent XSS attacks.

examples/echo-xss-secure.php

<?php
use Phppot\UI;
require_once __DIR__ . '/../vendor/Phppot/Util.php';
$util = new Util();
$inputString = '<canvas id=\'target\'></canvas>';
$util->xecho($inputString);
$util->echoSafe($inputString);
?>

vendor/Phppot/Util.php

<?php
/**
 * Copyright (C) Vincy - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Vincy <vincy@phppot.com>
 */
namespace Phppot;

class Util
{

    public function echoSafe($data)
    {
        echo $this->makeSafe($data);
    }

    public function xssafe($data, $encoding = 'UTF-8')
    {
        return htmlspecialchars($data, ENT_QUOTES | ENT_HTML401, $encoding);
    }

    public function xecho($data)
    {
        echo $this->xssafe($data);
    }

    /**
     * Escape all HTML, JavaScript, and CSS.
     * Convert all applicable characters to HTML entities.
     *
     * @param string $input
     *            The input string. In general, string received via user input.
     * @param string $encoding
     *            Character encoding used.
     * @return string Converts all applicable characters to HTML entities
     */
    public function makeSafe($data, $encoding = 'UTF-8')
    {
        return htmlspecialchars($data, ENT_QUOTES | ENT_HTML5, $encoding);
    }
}

safe echo

Related print statement in PHP

There are more print statements in PHP. We have seen some of them in the above sections. For example: print_r() to print an array.

  1. print()
  2. print_r()
  3. printf()
  4. flush()

The printf() outputs a formatted string and the flush() outputs buffer.

Conclusion

We have seen an overview of PHP echo with syntax and routine practices. The examples we have created for this article will help you to understand the usage.

The custom echo functions are useful for preventing XSS attacks. It will be safe to use these functions in a live application.

The related list of functions provides knowledge about different print statements in PHP.

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP echo to print HTML, New Line, Text and Array”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page