Display array structure and values in PHP 7

PHPServer Side ProgrammingProgramming

An array in PHP is a type of data structure that can store multiple elements of similar data type under a single variable.

To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.

Difference between print_r and var_dump

print_r: It is used to display the variable information in a human-readable format. Array values will be present in a format so that keys and elements can show. print_r also shows protected and private properties of objects but it will not show the static class and members.

Example

Live Demo

<?php
   $x = array ('x' => 'Dept', 'y' => 'Employee', 'z' => array ('a', 'b', 'c'));
   print_r ($x);
?>

Output

Output for the above print_r program will be:

Array
(
   [x] => Dept
   [y] => Employee
   [z] => Array
      (
         [0] => a
         [1] => b
         [2] => c
      )
)

var_dump: It is used to display the structure information of one or more variables and expressions including its type and value. Arrays and objects are explored recursively with their values indented to show the structure.

Example

Live Demo

<?php
   $x = array(1, 2,3, array("x", "y", "z","a"));
   var_dump($x);
?>

Output

Output for the above var_dump program will be −

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"
   }
}

Program using print_r and var_dump statement

Example

Live Demo

<?php
   $students = array("Rohan", "Mohan", "Thomas"); // it will print the students
   print_r($students);
   //echo "<hr>";
   var_dump($students);
?>

Output

The output for the above program will be −

Array
(
   [0] => Rohan
   [1] => Mohan
   [2] => Thomas
)
array(3) {
   [0]=>
   string(5) "Rohan"
   [1]=>
   string(5) "Mohan"
   [2]=>
   string(6) "Thomas"
}
raja
Published on 13-Mar-2021 11:32:04
Advertisements