w3resource

PHP: print_r() function

Description

The print_r() function is used to print human-readable information about a variable.

Version:

(PHP 4 and above)

Syntax:

print_r(var_name, return_output)

Parameter:

Name Description Required /
Optional
Type
var_name The variable being printed. Required String
return_output To capture the output in a variable, the parameter should set TRUE. The default value is FALSE. Optional Boolean

Return value:

If the variable is an integer or a float or a string the function returns value of the variable. If the variable is an array the function returns keys and elements, a similarly notation is used for the object. Setting TRUE to return_output parameter the function returns a string

Example -1:

<?php
$var1='abc';
$var2=123.33;
print_r($var1);
echo'<br>';
print_r($var2);
echo'<br>';
$abc = array('Subj1'=>'Physics','Subj2'=>'Chemistry','Subj3'=>'Mathematics','Class'=>array(5,6,7,8));
print_r($abc);
?>

Output :

abc
123.33
Array  (      [Subj1] => Physics      [Subj2] => Chemistry      [Subj3] => Mathematics      [Class] => Array          (              [0] => 5              [1] => 6              [2] => 7              [3] => 8          )    ) 

View the example in the browser

Practice here online :

Example -2 :

In the following example, the second parameter of the function has used, capture the output of the function in a variable then print the output with echo.

<?php
$var1='abc';
$result = print_r($var1);
echo $result.'<br>';
$var2=123.33;
$result = print_r($var2);
echo $result.'<br>';
$abc = array('Subj1'=>'Physics','Subj2'=>'Chemistry','Subj3'=>'Mathematics','Class'=>array(5,6,7,8));
$result = print_r($abc);
echo $result.'<br>';
?> 

Output:

abc
      123.33
      Array  ( [Subj1] => Physics [Subj2] => Chemistry [Subj3] => Mathematics [Class] => Array ( [0] => 5              [1] => 6  [2] => 7   [3] => 8  )    ) 

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: isset
Next: serialize



PHP: Tips of the Day

PHP: PHP Constants Containing Arrays?

NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays

You can also serialize your array and then put it into the constant:

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);

Ref : https://bit.ly/2EcIer8