PHP print_r() function

The PHP "print_r()" function is used to print information of a specified variable and looks more readable. Or we can say that the print_r() function is used to print an array, object, or variable's contents in a human-readable format. Debugging and comprehending the composition and contents of complex data types are facilitated by it. For example:

<?php
   $x = array("Berlin", "London", "NewYork", "Munich");
   print_r($x);
?>

The output of the above PHP example on the print_r() function is:

php print_r function

See the output of $x, an array variable. We can clearly see that, at index 0, the Berlin is stored. Similarly, at index 1, London is stored, and so on. That is, if you use the following PHP statement:

echo $x[0];

Then you will get Berlin as an output.

PHP print_r() syntax

The syntax of the print_r() function in PHP is:

print_r(variable, return)

The first parameter (variable) is required, whereas the second parameter (return) is optional.

The "variable" parameter is used to specify the variable about which we want to print information.

Note: The default value of the return parameter is false. But if we specify this parameter as true, then the function print_r() returns the information without printing.

Note: If the variable parameter is an integer, float, or string type value, then the function print_r() prints the value itself. Whereas if the variable parameter is an array or an object, then it returns the information about the variable in the form of keys and elements.

Advantages of the print_r() function in PHP

Disadvantages of the print_r() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »