PHP print_r() Function

What is PHP print_r() Function?

If you want to display information of a variable that human can read easily, then use print_r() function. It is useful for inspecting structure and values of arrays and objects.

Syntax:

print_r(variable, return)

Parameters:

The Function has 1 required parameter and 1 optional parameter-

variable (Required): It specifies a variable whose information we want to display.

return (Optional): It specifies whether the function should return the output instead of displaying or not. It can take 2 values-

  • TRUE – If it is TRUE, the function return the output.
  • FALSE – If it is FALSE, the function doesn’t return the output, instead, it displays it. It is the default value.

Return Values:

  • When the second parameter “return” is FALSE, the function returns 1.
  • When the second parameter “return” is TRUE, the function returns the output.

Examples:

Example 1:

<pre>
<?php
$languages = array("Markup" => "HTML", "Styling" => "CSS", "Scripting" => "Javascript", "Serverside" => "PHP");
$return_val = print_r($languages);
?>
</pre>

Output:

Array
(
[Markup] => HTML
[Styling] => CSS
[Scripting] => Javascript
[Serverside] => PHP
)

Example 2:

<pre>
<?php
$languages = array("Markup" => "HTML", "Styling" => "CSS", "Scripting" => "Javascript", "Serverside" => "PHP");
$output = print_r($languages, true);
echo "The stored value is- \n" . $output;
?>
</pre>

Output:

The stored value is- 
Array
(
[Markup] => HTML
[Styling] => CSS
[Scripting] => Javascript
[Serverside] => PHP
)

Practical Usages of print_r() Function:

  • It is used in debugging to understand the structure and values of complex data types like arrays and objects.
  • It can display private and protected properties of an object which is helpful for debugging class instances. And, it ignores static class members.

Alternative to print_r() Function:

var_dump() is an alternative function to the print_r() function. var_dump() function also displays data types and length of the variable.

Notes:

Not to mention that the function can also a string, integer, or float type variable.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP print_r() Function

print_r() is a built-in variable handling function. Use this function when you need to see a cleaner output of a complex data type in human readable format.

Reference:

https://www.php.net/manual/en/function.print-r.php