PHP has two ways to display output to the screen:
The main difference between the two is the
echo command does not provide a return value, making it marginally faster than
echo 'Hello World!';
echo ("Hello World!");
print 'Hello World!'
print ("Hello World!");
// Hello World!
Each statement is not limited to use on a single line of code. You can spread your string across multiple lines as needed:
Here is the first line.
Here is the second line.
Escaping Single Quotes
If you're outputting text using single quotes but have a word with an apostrophe, you'll need to escape the apostrophe with a backslash
\ character to prevent errors:
echo 'I didn\'t know this would work!';
Join Strings Example
You can join two strings together into a single string:
$str1 = "Hello World!";
$str2 = "Have a nice day!";
echo $str1 . " " . $str2;
// Hello World! Have a nice day!
Another great thing about each statement is you can output a variety of strings, including HTML:
<p>Have a nice day!</p>
Array values can be added to a string using the following example:
$array = ["apples", "oranges"];
echo 'My two favorite fruits are ' . $array . ' and ' $array;
Similarly, you can add object values to a string and output accordingly:
$array = [
"fruit" => "orange"
echo 'If I had to pick one fruit, it would be an ' . $array["fruit"];
As you can see, the