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.
<?php 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.
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
echo doesn't need parenthesis, although you can use parenthesis if you want.
<?php echo "I am open"; echo ("I am enclosed in parenthesis"); ?>
I am open I am enclosed in parenthesis
Let's see a few usecases where
echo is generally used.
We have already covered it multiple times, still:
<?php echo "I am a sentence"; ?>
I am a sentence
Here is how you can use multiple strings as parameters for
<?php echo 'This','is','a','broken','sentence'; ?>
This is a broken sentence
<?php echo "This is a multiline sentence example"; ?>
This is a multiline sentence example
<?php $str = "I am a string variable"; echo $str; ?>
I am a string variable
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
<?php $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.
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:
<?php 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.
echo, with same syntax and same usage. Just replace