Echo and Print Statement Difference in PHP
Echo and print in PHP are very similar to each other. Especially for the beginners, its difficult to figure out the difference between echo and print in PHP as both of the statements can be used in order to achieve the same goal.
Comparison between Print and Echo in PHP
|Comparison By||Echo In PHP||Print in PHP|
|Multiple Expressions||Can accept multiple expressions||Can’t accept multiple expressions|
|Return Value||Echo has no return value||Print always return value 1|
|Speed||Echo is relatively faster than print in PHP||Print is relatively slower than echo in PHP|
|Multiple arguments||Echo can pass more than one string separated by comma (,)||Print can’t pass more than one argument|
But if you look deep in those statements then you can easily identify the basic internal difference between echo and print.
I can write those difference one by one, But I think if I explain each difference with the proper example that will be better for you to understand.
Print statement and echo statement – general information
The print and echo both are used to print some data on your browser.
The below code is the basic way to print text on the browser using echo
<?php echo "This is some text"; ?>
And this below code is to print some text on the browser using the print statement
<?php print "This is some text"; ?>
In both echo and print statement, we can use parenthesis.
Difference between echo and print in PHP
One major difference is multiple arguments passing.
let’s understand this with a small example.
<?php $website="CodeSpeedy"; $purpose="is a coding solution website"; echo $website,$purpose; ?>
CodeSpeedyis a coding solution website
<?php $website="CodeSpeedy"; $purpose="is a coding solution website"; print $website,$purpose; ?>
Parse error: syntax error, on line 5
So you can now understand that multiple arguments can be passed in echo statement but not in print.
Or you can say that print statement is not able to accept multiple expressions but echo statement in PHP can accept multiple expressions.
Another major difference between print and echo in PHP is Return Type.
Echo does not return value but print always return value 1.
Let’s understand what it means by the following easy example-
If we use echo the code will be like this
<?php $name="CodeSpeedy"; $new_name=echo $name; echo $new_name; ?>
Parse error: syntax error, unexpected 'echo' (T_ECHO)on line 4
Here we got an error as
$new_name= echo $name
echo $name cannot be used for returning any value so we have received an error.
If we use print then the code will be like this
<?php $name="CodeSpeedy"; $new_name=print $name; echo $new_name; ?>
Here we just declared the variable $name with the value CodeSpeedy and Assigned another variable $new_name which will hold the value of print $name return.
So here we will get the value of $name as output with return type 1.