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>
	<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>PHP Example</title>
	</head>

	<body>

	<?php
	echo "<p>Welcome</p>";
	echo "<p>This is an example</p>";
	echo "<p><a href=\"http://www.google.com/\">Google</a></p>";
	echo '<p><a href="http://www.google.com/">Google</a></p>';
	?>
	
	</body>
	</html>
	

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.


	<?php
	$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:

55

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


	<?php
	$x = 2;
	$y = 3;
	echo $x + $y;
	print $x + $y;
	?>
	</code>
	

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.


	<?php
	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


	<?php
	echo "<ul>
			<li>Apples
			<li>Oranges
			<li>Grapes
		  </ul>";	
	?>
	

Run it now