HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Output (echo / print)

To display data or HTML in a browser using PHP, you primarily use two statements: echo and print. While they perform almost identical tasks, there are small differences in how they function under the hood.


1. The echo Statement

echo is the most commonly used output statement in PHP. It is slightly faster than print and can take multiple parameters (though this is rarely used).

<?php
    echo "Hello World!";
    echo "<h3>PHP is Fun!</h3>";
    echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>

You can use echo with or without parentheses: echo or echo().


2. The print Statement

print works very similarly to echo. The key difference is that print always returns a value of 1, meaning it can be used in expressions.

<?php
    print "Hello World!";
    print "<p>I am learning PHP!</p>";
?>

Displaying Variables

Both echo and print are used to output variable values on the screen. Note how we use the dot operator (.) for string concatenation.

<?php
    $txt1 = "Learn PHP";
    $txt2 = "RedoHub";
    $x = 5;
    $y = 4;

    echo "<h2>" . $txt1 . "</h2>";
    echo "Study PHP at " . $txt2 . "<br>";
    echo $x + $y;
?>
Double Quotes vs Single Quotes: Inside double quotes (" "), PHP will process variables automatically. Inside single quotes (' '), it will display the variable name literally.
<?php
    $name = "Alice";
    echo "Hello $name"; // Outputs: Hello Alice
    echo 'Hello $name'; // Outputs: Hello $name
?>

Differences at a Glance

Feature echo print
Speed Slightly faster Slightly slower
Return Value No return value Returns 1 (can be used in expressions)
Parameters Can take multiple strings Takes only one argument
Pro Tip: Most developers use echo by default unless there is a specific need for a return value. It is the industry standard for sending HTML to the browser.

Key Points to Remember

  • echo and print are used to output data to the browser.
  • echo is faster and more versatile (multiple parameters).
  • print returns 1, allowing it to be used inside logic/expressions.
  • Use concatenation (.) to join strings and variables.
  • Variables inside double quotes are parsed; inside **single quotes** they are literal.