PHP Echo / Print
PHP provides two primary methods for outputting data: echo and print.
Echo
echo is a language construct used to output one or more strings. It can take multiple parameters but is rarely used that way.
Usage Example
<?php
echo 'Hello, World!'; // Outputs: Hello, World!
?>
Output:
Hello, World!
Explanation: The echo
statement is used to output the string Hello, World! directly to the web page.
print is a language construct that outputs a string and returns 1. It can only take one argument.
Usage Example
<?php
print 'Hello, World!'; // Outputs: Hello, World!
?>
Output:
Hello, World!
Explanation: The print
statement is similar to echo
, and it outputs the string Hello, World! to the web page.
Outputting JSON
Example of encoding a PHP array to JSON and outputting it:
<?php
header('Content-Type: application/json');
$data = array('name' => 'John', 'age' => 30);
echo json_encode($data);
?>
Output:
{"name":"John","age":30}
Explanation: This code sets the content type to JSON and outputs a JSON-encoded string representing a PHP array.