New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

PHP echo and print functions

In this tutorial we will learn about two of the most important methods of PHP which are not built-in functions of PHP language, but they are language constructs.

    echo "Hello, I am a language construct";

You must be wondering, What is a language construct? A language construct is accepted/executed by the PHP parser as it is, in other words th PHP parser doesn't have to parse and modify a language construct to execute it, as it is ready for execution by default. Hence, language constructs are faster than any built-in functions.

PHP Echo

echo() function is used to print or output one or more strings. We have specifically mentioned string here because, the syntax of the echo function is:


Although you can use echo() function to output anything, as PHP parser will automaticallly convert it into string type.

echo doesn't need parenthesis, although you can use parenthesis if you want.

    echo "I am open";
    echo ("I am enclosed in parenthesis");

I am open I am enclosed in parenthesis

Time for Example

Let's see a few usecases where echo is generally used.

Printing a basic sentence

We have already covered it multiple times, still:

    echo "I am a sentence";

I am a sentence

Printing multiple strings using comma ,

Here is how you can use multiple strings as parameters for echo.

    echo 'This','is','a','broken','sentence';

This is a broken sentence

Printing a multiline text(string)

    echo "This is a
     multiline sentence

This is a multiline sentence example

Printing a string variable

    $str = "I am a string variable";
    echo $str;

I am a string variable

Printing a string variable with some text

Below we have explained how using double quotes and single quotes leads to different output when we use a string variable with some plain text in echo.

    $weird = "Stupid";
    echo "I am $weird";
    echo 'I am $weird';

I am Stupid I am $weird

As you can see, when we use double quotes the value of the string variable gets printed, while if we use single quotes, the variable is printed as it is.

Escaping special characters

As seen in previous examples, a double quote is required by echo to confirm what has to be printed. But what if you want to print the double quotes too? In such cases, we use an escape sequence to escape special characters from their special meanings. In PHP, a backslash \ is used to escape special characters.

Below we have a simple example:

    echo "Hello, this is a \"beautiful\" picture";

Hello, this is a "beautiful" picture

As you can see, the double quotes are printed in the output.

PHP Print

The PHP print is exactly the same as echo, with same syntax and same usage. Just replace echo with print in all the above examples, and they will work just fine.