Echo or Print?
There are 2 main functions that are commonly used by PHP developers to output a string: echo and print. The question is, which one is better?
They are fairly do the same exact thing, but echo is definitely faster than print.
Are Parentheses Required?
Here’s the fact: echo and print are both not actually a real function, but they are language constructs, so we are not required to use parentheses with its argument list.
All of the following statements are correct:
echo "Hello World!";
print "Hello World!";
Single or Double Quotes?
Given the following examples:
echo "My name is $name";
echo 'My name is $name';
The first statement would output something similar to “My name is Irwan“, while the second statement would output exactly “My name is $name“. Why? Because double quotes parse variables, while single quotes don’t.
Should we always use double quotes? No. Single quotes are at least 4 times faster than double quotes in any situation. We should always use single quotes whenever possible.
This is better:
echo 'My name is ' . $name;
This is tricky, which of these statements are the fastest?
echo "My name is $name and I am still learning PHP";
echo "My name is " . $name . " and I am still learning PHP";
echo 'My name is ' . $name . ' and I am still learning PHP';
echo 'My name is ' , $name , ' and I am still learning PHP';
In the above, we have learned that single quotes are always faster than double quotes. So it’s between statement 3 and 4. Since echo is a language construct that accepts parameters, we can use comma-separated parameters instead of string concatenation. The answer: Statement 4 is the fastest because the PHP compiler will save time on concatenating strings.