PHP Variable Handling print_r() Function



The PHP Variable Handling print_r() function is used to display information about a variable in an understandable format. It is useful for checking the contents of an array or object. This function prints the data in a simple format, including keys and values. It works with a variety of data types, including numbers, texts, arrays, and objects.

If you call print_r() with an object, it will display both private and protected properties. But it does not display the static properties of a class. You can also save the output as a string rather than printing it on the screen. To accomplish this, set the second parameter ($return) to True.

Syntax

Below is the syntax of the PHP Variable Handling print_r() function −

string|true print_r ( mixed $value, bool $return = false )

Parameters

Below are the parameters of the print_r() function −

  • $value − It is the variable whose details you want to print.

  • $return − If set to true, the function will return the output as a string instead of printing it.

Return Value

If you give a string, integer, or float, the value will be printed. If you give an array, the values will be shown in a manner with keys and elements. Objects are represented with similar notation.

When the return parameter is set to TRUE, the function returns a string. Otherwise, the return value is TRUE.

PHP Version

First introduced in core PHP 4, the print_r() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP Variable Handling print_r() function with a string and an integer. It prints the values directly on the screen.


Output

Here is the outcome of the following code −

Hello, PHP!
100

Example 2

In the following program we will show how print_r() display the elements of an array with the keys and values.

 

Output

This will generate the below output −

Array
(
   [0] => Apple
   [1] => Banana
   [2] => Orange
)

Example 3

Now the below code defines a class and uses print_r() to display its properties like private and protected ones.

 

Output

This will create the below output −

Car Object
(
   [brand] => Toyota
   [model:Car:private] => Urban Cruiser Taisor
   [year:protected] => 2024
)

Example 4

In the following example, we are using the print_r() function for storing output as a string. The program captures the output of the function in a variable instead of printing it directly.

 

Output

Following is the output of the above code −

Stored Output:
Array
(
   [0] => Red
   [1] => Blue
   [2] => Green
)
php_variable_handling_functions.htm
Advertisements