PHP print_r() function

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.

Syntax

snippet
print_r (mixed $var_name, boolean $return_output)

Parameters

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.

Return Values

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.

Examples

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.

snippet
<?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

Output
Integer Value: 501 Float Value: 22.4 String Value: Welcome to rookienerd!

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

snippet
<?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

Output
Array ( [x] => Windows [y] => Mac [z] => Array ( [0] => Linux [1] => Unix [2] => iOS ) )
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +