Back to the Basics: print vs echo šŸ¤œ šŸ¤›

nahi3an

Nafis Nahiyan

Posted on August 12, 2023

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.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
nahi3an
Nafis Nahiyan

Posted on August 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related