PUBLISHED ON: AUGUST 7, 2021
How to display array structure and values in PHP?
Answer: Using print_r()
function
We can display the array structure and values in PHP using the print_r()
function. The print_r()
function prints the information about the array elements in a more readable form.
Example: Displaying array structure and values
In the given example, we have displayed the array structure and values using the print_r()
function.
<!DOCTYPE html>
<html>
<head>
<title>Displaying array structure and values</title>
</head>
<body>
<?php
$arr = array(1, 2, 3, 4, 5, 6, 7, 8);
print_r($arr);
?>
</body>
</html>
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )
Using var_dump()
function
We can also display the array structure and values using the var_dump()
function. The var_dump()
function shows the information about the particular variable and array. In the case of an array, it displays information such as the type of the array element, its value, etc.
Example: Displaying array structure and values
In the given example, we displayed the array structure and values using the var_dump()
function.
<!DOCTYPE html>
<html>
<head>
<title>Displaying array structure and values</title>
</head>
<body>
<?php
$arr = array(1, 2, 3, 4, 5, 6, 7, 8);
var_dump($arr);
?>
</body>
</html>
array(8) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(8) }
Conclusion
In this lesson, we have learned how to display array structure and values in PHP. At first, we have used the print_r()
function to display the array structure and values. Then we have used the var_dump()
function to print the array structure and values.