PHP Echo/Print

In PHP, echo and print are both language constructs used to output data to the screen. They are similar, but there are some subtle differences between them that are worth noting. Here's a detailed comparison of echo and print:


1) echo statement


echo is a language construct (not actually a function) used to display one or more strings.


Syntax:


echo "Hello, World!"; 


Key Characteristics:


  • Can output multiple strings separated by commas (but without parentheses).
Example
<!DOCTYPE html>
<html>
<body>

<?php
echo "Hello, ", "World!"; // Outputs: Hello, World!
echo "This is a simple output.";

?>

</body>
</html>

Try it yourself

  • Does not return a value, so it cannot be used in expressions.
Example
<!DOCTYPE html>
<html>
<body>

<?php

$ret = echo "This is a simple output."; //Output: Parse Error
echo $ret;

?>

</body>
</html>

Try it yourself

2)  print statement


print is also a language construct used to output data to the screen, similar to echo.


Syntax:


print "Hello, World!";


Key Characteristics:


  • Can only output one string and does not accept multiple parameters like echo.
Example
<!DOCTYPE html>
<html>
<body>

<?php

print "<h2>PHP is Fun!</h2>";
print "This is a simple output.<br>"; // Outputs: This is a simple output.
print "Hello, World!"; // Outputs: 1 (because print returns 1)

?>

</body>
</html>

Try it yourself

  • Always returns a value of 1. This allows it to be used in expressions (e.g., in conditions).
Example
<!DOCTYPE html>
<html>
<body>

<?php
$lang = "PHP";
$ret = print $lang." is a web development language.";
print "</br>";
print "Value return by print statement: ".$ret;

?>

</body>
</html>

Try it yourself

Which One Should You Use?


  • For simple output: Use echo for its speed and flexibility with multiple parameters.
  • For conditional expressions: Use print since it returns a value.

In most cases, echo is more commonly used in PHP scripts due to its simplicity and speed. However, understanding the nuances of both can help you choose the right one for specific scenarios.

Note

The main difference between the print and echo statement is that echo does not behave like a function whereas print behaves like a function.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.