Display array structure and values in PHP 7

An array in PHP is a data structure that can store multiple elements under a single variable. To display array structure and values in PHP, we can use print_r() or var_dump() functions to show array contents in human-readable format.

Using print_r()

The print_r() function displays variable information in a human-readable format, showing array keys and elements clearly −

<?php
    $x = array('x' => 'Dept', 'y' => 'Employee', 'z' => array('a', 'b', 'c'));
    print_r($x);
?>
Array
(
    [x] => Dept
    [y] => Employee
    [z] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )
)

Using var_dump()

The var_dump() function displays detailed structure information including data types and values −

<?php
    $x = array(1, 2, 3, array("x", "y", "z", "a"));
    var_dump($x);
?>
array(4) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
    [3]=>
    array(4) {
        [0]=>
        string(1) "x"
        [1]=>
        string(1) "y"
        [2]=>
        string(1) "z"
        [3]=>
        string(1) "a"
    }
}

Comparing Both Functions

Here's an example using both functions on the same array −

<?php
    $students = array("Rohan", "Mohan", "Thomas");
    
    echo "Using print_r():
"; print_r($students); echo "\nUsing var_dump():
"; var_dump($students); ?>
Using print_r():
Array
(
    [0] => Rohan
    [1] => Mohan
    [2] => Thomas
)

Using var_dump():
array(3) {
    [0]=>
    string(5) "Rohan"
    [1]=>
    string(5) "Mohan"
    [2]=>
    string(6) "Thomas"
}

Key Differences

Feature print_r() var_dump()
Data Types Not shown Shows detailed types
String Length Not shown Shows character count
Readability More readable More technical

Conclusion

Use print_r() for simple, clean array display and var_dump() when you need detailed type information for debugging purposes.

Updated on: 2026-03-15T09:40:25+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements