Back to the Basics: print vs echo š¤ š¤
Nafis Nahiyan
Posted on August 12, 2023
print & echo or print() & echo() however you write them, are both used in php for the same purpose, printing out a value (int, bool, float, string & null). Though they both serve the same purpose there are some key differences between them. Let's explore them with an example:
š Print returns an integer value of 1 but echo returns nothing or void.
For example, if we do this :
$name = "Oppenheimer";
$res = print $name . "\n"; # ā
adding a new line for more readability
var_dump($res); # ā
this gives us int(1) , which means print return an integer data type & value is 1
But when we try this there is a problem :
$res = echo $name . "\n"; # šØ this gives full-on error: Parse error: syntax error, unexpected token "echo" because the return type of echo is void
Now if we want we can use the return value of print if we want but this will not come in handy for a real-life example. For the sake of example let's do this:
$quantity = 5;
$price = 10;
$total = $quantity * $price + print "The price is: {$price} \n"; # ā
first print executes its printing command then it returns 1 which is added to the total value
echo "The total is: {$total}"; # so this gives us The total is 51
š Echo takes multiple parameters but print does not do this. For example, let's see this code :
$firstName = "John";
$lastName = "Doe";
$age = 30;
echo "Name:", $firstName, " ", $lastName, ", Age:", $age; # ā
passing multiple parameters to echo function separated by comma ( , )
But when we try this there is a problem :
print "Name:", $firstName, " ", $lastName, ", Age:", $age; #šØ PHP Parse error: syntax error, unexpected token "," because the print function cannot take multiple parameters
š Lastly echo is slightly faster than print because it does not return anything
So these are some main differences between print and echo in the world of PHP. Thank you for reading.
Posted on August 12, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.