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 - how to create a newline character?

Only double quoted strings interpret the escape sequences \r and \n as '0x0D' and '0x0A' respectively, so you want:

"\r\n"

Single quoted strings, on the other hand, only know the escape sequences \\ and \'.

So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string "\r\n" or using chr function chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:

$s = 'some text before the line break
some text after';

Make sure to check your editor for its line break settings if you require some specific character sequence (\r\n for example).

Ref : https://bit.ly/3hcyege