DEV Community

Cover image for Back to the Basics: print vs echo 🤜 🤛
Nafis Nahiyan
Nafis Nahiyan

Posted on

Back to the Basics: print vs echo 🤜 🤛

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

📌 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 ( , )
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

📌 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.

Top comments (0)