Loading...

What is PHP echo and print statement?

what-is-php-echo-and-print-statement

What is PHP echo and print statement?

  • study365days.in

In PHP, both `echo` and `print` are used to output text or data to the browser or client. They are commonly used to display dynamic content within HTML documents. However, there are some differences between the two:

  1. `echo` Statement:
    The `echo` statement is a language construct and not a function. It can take multiple arguments separated by commas and doesn't require parentheses. It outputs the specified text or variables to the browser.

Example: 

<?php
 $name = "John";
 echo "Hello, " . $name . "!"; // Outputs: Hello, John!
?>
        
  1. `print` Statement:
    The `print` statement is also used to output text, but it's a language construct similar to `echo`. Like `echo`, it can take multiple arguments and doesn't require parentheses. However, it returns a value of 1, so it can be used within expressions.

Example:
 

<?php
 $message = "Welcome";
 $result = print $message; // Outputs: Welcome and assigns 1 to $result
?>        

While both `echo` and `print` can be used to achieve similar results, `echo` is more commonly used due to its slightly better performance and versatility. You can use `echo` with or without parentheses, and it works with multiple arguments. On the other hand, `print` is mostly used in specific cases where you need its return value in an expression.

Example usage of `echo`:
 

<?php
 echo "Hello", " ", "World"; // Outputs: Hello World
?>        

Example usage of `print`:
 

<?php
 $result = print("Hello"); // Outputs: Hello and assigns 1 to $result
?>        

In most scenarios, `echo` is preferred due to its simplicity and efficiency.