php
  1. php-print-r-function

Php print_r() Function

The print_r() function is a built-in function in PHP that prints human-readable information about a variable. It can be used to print the values of PHP variables, arrays, or objects in a well-organized and easy-to-read manner.

Syntax

The syntax for the print_r() function is:

print_r($variable, $return = false)

Where:

  • $variable: The variable that you want to print.
  • $return: (Optional) If set to true, it returns the information instead of printing it.

Example

Consider the following example:

<?php

$numbers = array(1, 2, 3, 4, 5);
print_r($numbers);

?>

Output

The output of the above example will be:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Explanation

The print_r() function takes a variable and prints its value in the form of a human-readable string. In the above example, we have an array of numbers that we pass to the print_r() function. The function then prints each element of the array along with its corresponding index.

Use

The print_r() function is mostly used for debugging purposes so that you can easily see the contents of a variable, array, or object. It is also useful when you want to see the structure of a complex object or array.

Important Points

  • The print_r() function can only print one variable at a time.
  • If you pass multiple variables to the print_r() function, it will only print the information for the first variable and ignore the rest.
  • If you set the $return parameter to true, the function will return the information as a string instead of printing it.

Summary

The print_r() function is a useful tool for debugging PHP code as it allows you to print the values of variables, arrays, and objects in a well-organized and easy-to-read manner. By simply passing a variable to the function, you can easily view its contents and structure.

Published on: