PHP Output Data

The easiest way we can output data in PHP is using a Language Construct known as echo. Constructs are elements that are built into language. 'echo' can be used for outputting any data. It can also be used to output HTML

Example of PHP echo:

<?php
echo "this is my first message.";

/* output: this is my first message. */
?>

PLEASE NOTE:

  • we end a php line with a semicolon
  • to echo some text (a string) you need to wrap it in between quotation marks
  • we will use comments to display the output of our scripts

The above example will show this message on webpage. this is my echo message.

You can use echo to output some HTML code:

<?php
echo "<p>this is my first paragraph.<p>";
echo "<p>this is my second paragraph.<p>";
echo "<p><strong>this is some bold text.</strong><p>";
/*
this is my first paragraph.

this is my second paragraph.

this is some bold text.
*/

?>

 

Other ways to output in PHP: print(), printf()

Another construct to output data is print:

<?php
print "<p>this is a paragraph 'printed' without parenthesis.<p>";
print( "<p>this paragraph is "printed" using parenthesis.<p>" );
/*
this is a paragraph 'printed' without parenthesis.

this paragraph is "printed" using parenthesis.
*/

?>

PLEASE NOTE:

  • you can nest single quotation marks inside double quotation marks (or the other way around)
  • you can escape some nested quotation marks using a backslash ()
  • as print is a construct, you can use it with or without parenthesis

A more complex way to output and format data is the printf() function:

<?php
//declaring a variable $myName = "John Doe";
printf
("<p>Hello, my name is <strong>%s</strong>.<p>", $myName);
/*
Hello, my name is John Doe.
*/

?>

PLEASE NOTE:

  • $myName is a variable, click here to read more about variables
  • %s is a data type specifier, click here to read about data types, or here to read about other specifiers for the printf() function