
PHP print_r() function
In PHP, print_r()
is a built-in function used for printing human-readable information about a variable. It is primarily used for debugging purposes to display the contents of arrays, objects, and other complex data structures in a more readable format.
Syntax:
The syntax for print_r()
is as follows:
print_r($variable);
Parameters:
$variable
: The variable you want to print.
Return Value:
Unlike echo
or print
, print_r()
does not return the information as a string. Instead, it directly outputs the information to the screen.
Example:
$fruits = array("apple", "banana", "orange");
echo "Using print_r():<br>";
print_r($fruits);
echo "<br><br>";
echo "Using echo to display the array directly:<br>";
echo $fruits;
Output:
Using print_r():
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Using echo to display the array directly:
Array
In the example above, we have an array $fruits
containing three elements. We use print_r($fruits)
to display the array’s content in a human-readable format. The print_r()
function formats the output with proper indentation, displaying the array and its elements.
Please note that print_r()
is not suitable for displaying data in a production environment or to end-users since its output is meant for debugging and development purposes. For production use, you should use a proper method for displaying data to the users, such as rendering data within HTML templates or converting complex data into a structured format (e.g., JSON) for API responses.
If you need to inspect complex data structures, print_r()
is a handy tool to visualize the contents of arrays, objects, or other variables quickly during development and debugging. For more advanced and detailed introspection of objects, you can also use var_dump()
or explore other debugging tools provided by PHP.