PHP: Output

Creating basic PHP programs and scripts begins with basic output. There are two commands to accomplish this in PHP: echo and print. In both cases, if you are creating a web page, the output should be a web page that will validate at the W3C validator. This means one should include the HTML DocType and other required tags as shown in the example below.

Example: Simple PHP Output with Hyperlink

Open in new window

Example: Simple PHP Output with Hyperlink

	<!DOCTYPE html>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>PHP Example</title>


	echo "<p>Welcome</p>";
	echo "<p>This is an example</p>";
	echo "<p><a href=\"\">Google</a></p>";
	echo '<p><a href="">Google</a></p>';

Run it now

Example: Single vs. Double Quotes

There is a difference between the use of double quotes versus single quotes in an echo statement. Single quotes will not print the output of a variable or function as evident in the example below.

	$y = 5 * 2;
	echo "<p>$y</p>";
	echo '<p>$y</p>';

Run it now

Example: The Importance of HTML Tags

The importance of including HTML tags in the echo or print can be seen in this next example. The output of this program is:


Versus 5 on one line and 5 on the next line.

	$x = 2;
	$y = 3;
	echo $x + $y;
	print $x + $y;

Example: echo vs. print

The PHP print and echo commands only differ in that print is a function and thus has a return value and thus can be used in expressions. Echo can take multiple parameters and can be faster. The example below demonstrates these differences as well as the use of a PHP comment/remark.

	echo "<p>Hello. ", "How are you today?</p>"
	// next line would produce an error so it's commented out
	// print "<p>Hello.", "How are you today?</p>"
	$a ? print "true" : print "false";     // print used in an expression
	print "<p>$a</p>";

Run it now

Example: Multi-line Echo

	echo "<ul>

Run it now