Hands-on with PHP — Outputs

< Home < PHP VariablesPHP Strings >

Outputs of Code Execution

A computer program is only as useful as the information that it can produce and communicate to its users. This information is termed output in computer programming and is usually communicated to the users via a computer screen. In PHP, you can print the output of a program using one of these five constructs as follows:

Note:

All of them are NOT case sensitive.

echo

echo is a PHP construct (a built-in feature of a computer language) for printing a string output made from one or more parameters. echo statements can be written in one of the three syntaxes as follows:

  • Single parameter
void echo arg
  • Single parameter with brackets
void echo ( arg )
  • Multiple parameters with commas
void echo arg1, arg2, ...

Regardless of the syntax that it takes,

echo does not have any return value.

echo() takes one or more arg parameters which can be literal values or variables.

Check out the example in the echo Syntax code section using the PhpFiddle widget.

<?php
$age = 2;
echo("He is $age years and 6 months old.<br>");
echo "He is $age years and 6 months old.<br>";
echo "He is ", $age, " years and ", "6", " months old.<br>";
echo "He is ", $age, " years and ", 6, " months old.";
/*
He is 2 years and 6 months old.
He is 2 years and 6 months old.
He is 2 years and 6 months old.
He is 2 years and 6 months old.
*/
?>

echo is most commonly used in PHP to output result produced by a PHP script on the web server to the client browser for displaying on a web page. You have already seen an example under How PHP Works? in the PHP Introduction lesson.

Check out the example in the echo Output code section using the PhpFiddle widget.

<?php
// Output spanning multiple lines in console
echo "This output spans
multiple lines in console
using keyboard-input newlines.

";

// Output spanning multiple lines using \n in console
echo "This output spans\nmultiple lines in console \nusing \\n\n\n.";
?>

<?php
// Single parameter with <h2> markup
echo "<h2>Single parameter with &lt;h2&gt; markup</h2>";

// Output spanning multiple lines in browser using <br> tag
echo "<p>This output spans<br>multiple lines in browser screen<br>using &lt;br&gt; markup.<p>"; 

$first_name = "Peter";
$last_name = "Leow";
// Variables embedded inside a parameter
echo "<p>My full name is $first_name $last_name.</p>";
?>

The output of the echo Output code in the PhpFiddle widget  is what you would have seen in a real browser.

  • What happens in the browser is that:

HTML markup is honoured.

Neither multi-line parameter nor \n is honoured. Insert <br> at each line break or enclosed them in a pair of <pre> and </pre> tags as shown in the following code snippet:

<?php
echo "<pre>";
echo "This output spans
multiple lines in console
using keyboard-input newlines.

";
echo "</pre>";

// Output spanning multiple lines using \n in console
echo "This output spans<br>multiple lines in console <br>using \\n<br><br>.";
?>

If you right click the output of the echo Output code in the browser and select View page source, you should see something that looks like this:

This output spans
multiple lines in console
using keyboard-input newlines.

This output spans
multiple lines in console 
using \n

.
<h2>Single parameter with <h2> markup</h2><p>This output spans<br>multiple lines in browser screen<br>using <br> markup.<p><p>My full name is Peter Leow.</p>

The is the raw output of the response returned from the server and  is what you would see in a console.

  • What happens in the console is that:

HTML markup is not honoured.

echo parameter can span multiple lines and its output will also be multiple lines identically.

Alternatively, you can insert newlines using \n or PHP_EOL constant.

  • Apart from the differences above, it is also observed that:

PHP Variables can be embedded inside echo parameters, which makes data-driven content possible.

echo parameters can include HTML code, which makes it possible to change the whole or part of the HTML page on the fly.

Return to Outputs of Code

print

print is the twin construct of echo. You can, therefore, use print in place of echo most of the time except that:

print does not support multiple parameters with commas.

In the echo Output code section above, replace all the echo with print, and re-run the code to see that print produces the same output as echo.

print has a return value of integer 1, thus it can be used for evaluation in an expression. Check out the code in the Return Value of PHP print code section to see an example of counting the number of times PHP print being used.

<?php
print "<pre>";
$count = print "PHP print statement returns ";
var_dump($count); // int(1)

$count = $count + print "Another PHP print statement\n";

print "You have used PHP print for ".($count + 1)." times";

print "</pre>";
?>

Return to Outputs of Code

printf()

printf() is a PHP function that outputs a formatted string. It takes the following form:

integer printf ( pattern, arg1, arg2, ... )

printf() has a return value indicating the length of the outputted string.

printf() does not add a newline to its output.

The pattern parameter consists of a mix of literal characters (excluding %) that are treated as they are, and at least one or more conversion specifiers that are to be replaced with the corresponding arg parameters (i.e. arg1, arg2, etc.) which are in turn converted into appropriate types or formats specified by the respective conversion specifiers.

printf() must have at least one conversion specifier and a corresponding parameter, i.e. arg1 is compulsory.

Each conversion specifier must start with a % sign followed by a type specifier that specifies a data type that a corresponding arg parameter should be treated. Run the code of the Type Specifiers code section in the PhpFiddle widget to printf() the full list of type specifiers and their effects.

<?php
// Note: %% returns a % sign, so %%s will return %s in the output
$arg1 = 75;
printf("The value %s as represented by the following type specifiers:<br>", $arg1);
printf("String %%s = %s<br>", $arg1);
printf("ASCII character %%c = %c<br>", $arg1);
printf("Signed decimal %%d = %d<br>", $arg1);
printf("Unsigned decimal %%u = %u<br>", $arg1);
printf("Scientific notation (lowercase) %%e = %e<br>", $arg1);
printf("Scientific notation (uppercase) %%E = %E<br>", $arg1);
printf("Floating-point number (locale aware) %%f = %f<br>", $arg1);
printf("Floating-point number (non-locale aware) %%F = %F<br>", $arg1);
printf("Shorter of %%e and %%f %%g = %g<br>", $arg1);
printf("Shorter of %%E and %%f %%G = %G<br>", $arg1);
printf("Binary %%b = %b<br>", $arg1);
printf("Octal %%o = %o<br>", $arg1);
printf("Hexadecimal (lowercase) %%x = %x<br>", $arg1);
printf("Hexadecimal (uppercase) %%X = %X<br>", $arg1);

printf("<br>");

$arg1 = -75;
printf("The value %s as represented by the following type specifiers:<br>", $arg1);
printf("Signed decimal %%d = %d<br>", $arg1);
printf("Unsigned decimal %%u = %u<br>", $arg1);

/*
  The value 75 as represented by the following type specifiers:
  String %s = 75
  ASCII character %c = K
  Signed decimal %d = 75
  Unsigned decimal %u = 75
  Scientific notation (lowercase) %e = 7.500000e+1
  Scientific notation (uppercase) %E = 7.500000E+1
  Floating-point number (locale aware) %f = 75.000000
  Floating-point number (non-locale aware) %F = 75.000000
  Shorter of %e and %f %g = 75
  Shorter of %E and %f %G = 75
  Binary %b = 1001011
  Octal %o = 113
  Hexadecimal (lowercase) %x = 4b
  Hexadecimal (uppercase) %X = 4B
  
  The value -75 as represented by the following type specifiers:
  Signed decimal %d = -75
  Unsigned decimal %u = 18446744073709551541
*/
?>

Additionally, you can insert optional modifiers between the % and the type specifier to further refine the format of the arg parameter. These include:

Optional Modifiers Description
+ A sign modifier to insert + sign in front of the arg parameter if it is a positive number.
' A padding modifier to specify that the letter followed immediately after it is to be used as padding. The default letter for padding is space. A padding modifier must be used together with the width specifier to be mentioned later.
- An alignment modifier to left-justifies the arg parameter. By default, it is right-justified.
[0-9] A width modifier to specify the minimum width of the arg parameter.
.[0-9] A precision modifier to specify the number of decimal digits for floating point parameter or the maximum length for a string parameter.

Note:

If multiple modifiers are used, they must be inserted in the same order as appeared above.

Check out the code in the Modifiers code section on the crafting of modifiers. Run the code to see the outcome.

<?php
echo "<pre>";
$string = "Hello world!";
printf("[%s]\n",$string);     // [Hello world!]
printf("[%20s]\n",$string);   // [        Hello world!]
printf("[%-20s]\n",$string);  // [Hello world!        ]
printf("[%'*20s]\n",$string); // [********Hello world!]
printf("[%.8s]\n",$string);   // [Hello wo]

$number = 123456;
printf("[%f]\n", $number);        // [123456.000000]
printf("[%.2f]\n", $number);      // [123456.00]
printf("[%+.2f]\n", $number);     // [+123456.00]
printf("[%+'*20.2f]\n", $number); // [          +123456.00]

echo "</pre>";
?>

Return to Outputs of Code

var_dump()

var_dump() is a PHP function that outputs structural information, i.e. data type and value, about its parameters. It takes the form of:

void var_dump ( arg1, arg2, ... )

var_dump() takes one or more arg parameters.

var_dump() does not have any return value.

var_dump() adds a newline to its output.

var_dump() is more useful for debugging purpose. You have already used it extensively in the PHP Data Types lesson.

Check out how var_dump() outputs different data types in the var_dump() code section.

<?php
echo "<pre>";

$name = "John Doe";

$age = 23;

$salary = 1234.56;

$shopping_list = array("Milk","Bread","Apple","Cheese");

var_dump($name, $age, $salary, $shopping_list);

/*
  string(8) "John Doe"
  int(23)
  float(1234.56)
  array(4) {
  [0]=>
  string(4) "Milk"
  [1]=>
  string(5) "Bread"
  [2]=>
  string(5) "Apple"
  [3]=>
  string(6) "Cheese"
  }
*/

echo "</pre>";
?>

Return to Outputs of Code

print_r()

print_r() is another PHP output function that takes an arg argument and an optional Boolean flag, by default FALSE, in the following form:

mixed print_r ( arg [, flag = FALSE ] )

If the arg parameter is a string, an integer, or a float, print_r() outputs the value of the arg parameter.

If the arg parameter is an array or object, print_r() outputs the keys and elements of that array or object.

print_r() will return TRUE if the optional Boolean flag is left out or is set to FALSE.

If the optional Boolean flag is set to TRUE, print_r() will return the value of its arg argument for further processing, such as assigning it to a variable, instead of outputting it to the screen.

print_r() does not add a newline to its output.

Like var_dump(), print_r() is more useful for debugging purpose. But unlike var_dump(), its output is more human-readable.

Check out the behaviour of print_r() in the print_r() code section.

<?php
echo "<pre>";
$name = "John Doe";
print_r($name);

echo("\n");

$age = 23;
print_r($age);

echo("\n");

$salary = 1234.56;
print_r($salary);

echo("\n");

$shopping_list = array("Milk","Bread","Apple","Cheese");
print_r($shopping_list);

echo("\n");

$my_shopping_list = print_r($shopping_list, TRUE);
echo "My shopping list: ", $my_shopping_list;

/*
  John Doe
  23
  1234.56
  Array
  (
    [0] => Milk
    [1] => Bread
    [2] => Apple
    [3] => Cheese
  )
  
  My shopping list: Array
  (
    [0] => Milk
    [1] => Bread
    [2] => Apple
    [3] => Cheese
  )
*/

echo "</pre>";
?>

What happens if you remove the TRUE or replace it with FALSE from $my_shopping_list = print_r($shopping_list, TRUE); of the print_r() code section?

Return to Outputs of Code

Quiz

<?php 
printf("%c", 65);
?>
What is the expected output from executing the PHP script in Listing 1?
A
Correct!
%c
Wrong!
65
Wrong!
Nothing.
Wrong!
Which one of the following PHP construct or function will output an integer 45 as int(45)?
var_dump()
Correct!
print_r()
Wrong!
printf()
Wrong!
print
Wrong!
echo
Wrong!
<?php 
print_r(123, true);
?>
What is the expected output from executing the PHP script in Listing 2?
Nothing.
Correct!
123
Wrong!
true
Wrong!
123, true
Wrong!

< Home < PHP VariablesPHP Strings >

Tagged with:

Speak Your Mind