In PHP, if you want to output anything to the output screen, the most common functions to use are the echo
and print
functions.
Apart from echo
and print
, there are a couple of other functions we can use to do any kind of printing to screen, including the print_r()
function.
print_r()
functionThe print_r()
function is part of the PHP standard library and displays information about a variable in a form that can easily be read by humans.
With the print_r()
function, the information contained in complex variables (such as arrays and objects) is stripped out to the users in a simple, comprehensible format.
print_r($value,$return);
The print_r()
function requires two parameters:
$value
: the variable whose value is to be output to the screen.
$return
: can be set as true
or false
. By default, this parameter is false
. If set to true
, the print_r()
function will not print the information to screen. The value of the variable will be returned which you can capture and use for further actions.
When a string, int, or float is passed as the $value
parameter, the value of the variable itself will be printed.
If it is an array, the array values will be printed in a key-value pair format. This also happens to the object variable.
Just like
var_dump()
andvar_export()
,print_r()
will show protected and private properties of objects.
Below is an example of how to use the print_r()
function:
<?php$a1 = array ("fruit" =>["apples", "oranges", "pears"]);$a2 = 'This is a string';$a3 = 5.6;//$array = array_push(array ("fruit" => $a1, "vegies" => $a2, "money" => $a3));print_r($a1);print_r($a2);//let use print_r to return a value and save it$ar3ref = print_r($a3, true);//use echo to print to output the returned valueecho "\n".$ar3ref;?>