0
0
PHPprogramming~5 mins

Echo vs print behavior in PHP

Choose your learning style9 modes available
Introduction

Echo and print are used to show text or values on the screen in PHP. They help you communicate results or messages to users.

When you want to quickly display a message or variable value on a webpage.
When you need to output multiple pieces of text or variables together.
When you want to check the value of a variable during debugging.
When you want to print a simple message and check if the output was successful.
Syntax
PHP
echo expression1, expression2, ...;
print expression;

echo can take multiple expressions separated by commas.

print takes only one expression and returns 1, so it can be used in expressions.

Examples
Echo prints the text "Hello, world!" to the screen.
PHP
echo "Hello, world!";
Print also prints the text "Hello, world!" but returns 1.
PHP
print "Hello, world!";
Echo can print multiple strings separated by commas.
PHP
echo "Hello", " ", "world!";
Print outputs "Hello" and returns 1, which is stored in $result and then printed.
PHP
$result = print "Hello";
echo "\nReturn value: ", $result;
Sample Program

This program shows how echo can print multiple strings at once. It also shows that print outputs a string and returns 1, which we print afterwards.

PHP
<?php
// Using echo to print multiple parts
echo "Hello", " ", "Echo!\n";

// Using print to print a string and capture return value
$returnValue = print "Hello Print!\n";
echo "Return value from print: ", $returnValue, "\n";
?>
OutputSuccess
Important Notes

Echo is slightly faster than print because it does not return a value.

Print can be used in expressions because it returns 1, echo cannot.

Both are language constructs, so you don't need parentheses unless you want to group expressions.

Summary

Echo can print multiple values separated by commas and does not return a value.

Print prints one value and returns 1, so it can be used in expressions.

Use echo for simple output and print when you need a return value.