PHP Echo / Print In English -

PHP Echo / Print In English

Printing Values in PHP: echo() vs print()

In PHP, you can print values using the echo() function. You can use parentheses with echo, but they are optional.

Example 1: Using echo

File: test.php

<?php 
  $name = "Rahul Kumar";
  echo $name."<br>";
  echo($name);
?>

Output:

Rahul Kumar
Rahul Kumar

In the example above, you can see that values can be printed with or without parentheses using echo. Additionally, PHP provides the print() function, which can also be used to print values.

Example 2: Using print()

File: test2.php

<?php 
  $name = "Rahul Kumar";
  print $name."<br>";
  print($name);
?>

Output:

Rahul Kumar
Rahul Kumar

Note: In these examples, <br> is used for a line break, and the dot (.) is used for string concatenation.

Difference Between echo() and print()

Example 3: Difference in Return Values

File: test3.php

<?php 
   $name = "Rahul";
   echo print($name)."<br>";
?>

Output:

Rahul
1

In the above example, print($name) prints the value of $name and then returns 1, which echo then prints.

Note:

  • The print() function always returns 1 whether the value is printed successfully or not, and even if the variable is not defined or initialized.

Example 4: print() with Undefined and Uninitialized Variables

File: test4.php

<?php 
  $name;
  echo print($name);
  echo print($nsame);
?>

Output:

Notice: Undefined variable: name in C:\xampp\htdocs\test\test.php on line 3
1
Notice: Undefined variable: nsame in C:\xampp\htdocs\test\test.php on line 4
1

In this example:

  • The first variable $name is declared but not assigned any value.
  • The second variable $nsame is not defined at all.
  • Despite these issues, print() still returns 1 after attempting to print each variable, demonstrating that it always returns 1, even in the presence of errors or undefined variables.

This shows the behavior differences between echo() and print() in handling and returning values in PHP scripts.

Leave a Comment