PHP print_r() is a built-in function that displays information about a variable in a human-readable way. It shows the information stored in a variable, which is easily understandable to the user.
There are two more functions similar to print_r() which are var_export(), and var_dump(). They display the private and protected properties of objects.
print_r (mixed $var_name, boolean $return_output)
The print_r() function accepts two parameters, which are described below:
var_name - It is a required parameter. This parameter specifies the variable about which the information is to be returned.
return_output - It is an optional parameter. Use this return_value parameter if you want to capture the output of print_r() function. It is a boolean type of parameter whose default value is FALSE.
If the given variable is an integer, float, or a string, the value of the variable will be returned and printed itself.
If the given variable is an array, the values will be printed in the form of keys and value. Similar notation can be used for objects.
If the $return_output parameter is set to TRUE, this function will return a string. Otherwise, it will return TRUE.
Below some list of examples are given through which you can understand the working of print_r() function -
Example 1
In the given example, the variables hold the integer, float, and string type values. Therefore, the value of the variable will be returned itself and printed.
<?php //integer variable $input1 = 501; print_r('Integer Value: '.$input1); echo "</br>"; //float variable $input2 = 22.4; print_r('Float Value: '.$input2); echo "</br>"; //string variable $input3 = 'Welcome to rookienerd!'; print_r('String Value: '.$input3); ?>
Output
Example 2
In the given example, the variable will contain an array. Therefore, values will be printed in the form of keys and value. See the below example
<?php //simple array $input1 = array("Honor 9 Lite", "One Plus", "Redmi"); print_r($input1); echo "</br>"; //associative array $input2 = array('x' => "Windows", 'y' => "Mac", 'z' => array ("Linux", "Unix", "iOS")); print_r($input2); ?>
Output