Open In App

How to display array structure and values in PHP ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to display the array structure and values in PHP. To display the array structure and its values, we can use var_dump() and print_r() functions.

It includes 

  • Array size
  • Array values
  • Array value with Index
  • Each value data type

We will display the array structure using var_dump() function. This function is used to dump information about a variable. This function displays structured information such as the type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.

Syntax:

var_dump( $array_name )

Parameters: The function takes a single argument $array_name that may be one single variable or an expression containing several space-separated variables of any type.

Return Type: Array Structure

Example: PHP Program to create an array and display its structure.

PHP




<?php
  
// Array with subjects
$array1 = array(
      '0' => "Python"
      '1' => "java"
      '2' => "c/cpp"
);
  
// Display array structure
var_dump($array1);
  
?>


Output

array(3) {
  [0]=>
  string(6) "Python"
  [1]=>
  string(4) "java"
  [2]=>
  string(5) "c/cpp"
}

Here, 

  • array(3) is the size of the array ( 3 elements)
  • string(6) is the data type of element 1 with its size
  • string(4) is the data type of element 2 with its size
  • string(5) is the data type of element 3 with its size

Array Values: We will display the array values by using the print_r() function. This function is used to print or display information stored in a variable.

Syntax:

print_r( $variable, $isStore )

Parameters:

  • $variable: This parameter specifies the variable to be printed and is a mandatory parameter.
  • $isStore: This is an optional parameter. This parameter is of boolean type whose default value is FALSE and is used to store the output of the print_r() function in a variable rather than printing it. If this parameter is set to TRUE then the print_r() function will return the output which it is supposed to print.

Return Value: Array with values.

Example: PHP program to display an array of values.

PHP




<?php
  
// Array with subjects
$array1 = array(
      '0' => "Python"
      '1' => "java"
      '2' => "c/cpp"
);
  
// Display array values
print_r($array1);
  
?>


Output

Array
(
    [0] => Python
    [1] => java
    [2] => c/cpp
)


Last Updated : 07 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads