PHP print_r() Tutorial

beginner
22 min

PHP print_r() Tutorial

Welcome to our comprehensive guide on using the print_r() function in PHP! This tutorial is designed for both beginners and intermediates, so let's dive right in. 🎯

Understanding print_r()

The print_r() function is a built-in PHP function that prints human-readable output of a variable. It's incredibly useful for debugging and understanding the structure of your data. πŸ’‘

Basic Usage

To use print_r(), simply call the function and pass the variable you want to inspect as an argument. Here's a simple example:

php
<?php $myVariable = "Hello, World!"; print_r($myVariable); ?>

When you run this code, PHP will output:

string(13) "Hello, World!"

This tells us that $myVariable is a string of length 13, and its content is "Hello, World!". βœ…

Array Example

Let's see how print_r() works with arrays. Here's an example:

php
<?php $myArray = array("Apple", "Banana", "Orange"); print_r($myArray); ?>

The output will be:

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

This shows us that $myArray is an array with three elements. βœ…

Object Example

Now, let's take a look at how print_r() works with objects:

php
<?php class Fruit { public $name; public $color; function __construct($name, $color) { $this->name = $name; $this->color = $color; } } $apple = new Fruit("Apple", "Red"); print_r($apple); ?>

The output will be:

Fruit Object ( [name] => Apple [color] => Red )

This shows us that $apple is an instance of the Fruit class, with a name of "Apple" and a color of "Red". βœ…

Nested Structures

print_r() can also handle nested structures. Here's an example with a nested array:

php
<?php $myNestedArray = array( "fruits" => array("Apple", "Banana", "Orange"), "vegetables" => array("Carrot", "Potato", "Cucumber") ); print_r($myNestedArray); ?>

The output will be:

Array ( [fruits] => Array ( [0] => Apple [1] => Banana [2] => Orange ) [vegetables] => Array ( [0] => Carrot [1] => Potato [2] => Cucumber ) )

This shows us that $myNestedArray is an array with two elements: "fruits" and "vegetables". Each of these elements is an array containing three elements. βœ…

Quiz

Quick Quiz
Question 1 of 1

What does the `print_r()` function do in PHP?

That's it for our introduction to the print_r() function in PHP! Remember, practice makes perfect, so feel free to experiment with print_r() in your own projects. Happy coding! πŸ“