Home > Article > Backend Development > Which methods in php can output all elements of an array?
3 methods: 1. Use "var_dump($array)" to output the data content and structure of the entire array, and print the type information of the elements; 2. Use "print_r($array)" to output the data of the array Content and structure; 3. Use foreach loop to traverse the array, and use echo to output the elements one by one in the loop.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php can output arrays Several methods for all elements
Method 1: Use var_dump() to output the array
The var_dump() function can convert the data content of the entire array and structures for output. You can also print multiple variables at the same time and give the type information of the variables.
The var_dump() function can output relevant information (type and value) of variables. When outputting an array, the array will recursively expand the values and display its structure through indentation.
<?php header("Content-type:text/html;charset=utf-8"); $array = array ( array("姓名"=>"张三","年龄"=>25,"性别"=>"男"), array("姓名"=>"李四","年龄"=>21,"性别"=>"男"), array("姓名"=>"娜娜","年龄"=>22,"性别"=>"女") ); var_dump($array); ?>
Method 2: Use print_r() to output the array
The print_r() function is used to print in a more understandable form Variables, the content and structure of the entire array can be output through the print_r() function, and the keys and elements will be displayed in a certain format.
<?php header("Content-type:text/html;charset=utf-8"); $array = array ( array("姓名"=>"张三","年龄"=>25,"性别"=>"男"), array("姓名"=>"李四","年龄"=>21,"性别"=>"男"), array("姓名"=>"娜娜","年龄"=>22,"性别"=>"女") ); echo '<pre class="brush:php;toolbar:false">'; print_r($array); ?>
Method 2: Use the foreach echo statement to output the array
The foreach statement loops through the array, and uses the echo statement in the loop to Elements are output one by one
Note: A one-dimensional array only requires one foreach statement, while a multi-dimensional array requires multiple nested foreach statements.
<?php header("Content-type:text/html;charset=utf-8"); $array= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); foreach ($array as $val){ // 遍历数组 //输出数组元素 echo $val."<br>"; } ?>
<?php header("Content-type:text/html;charset=utf-8"); $array = array ( array("姓名"=>"张三","年龄"=>25,"性别"=>"男"), array("姓名"=>"李四","年龄"=>21,"性别"=>"男"), array("姓名"=>"娜娜","年龄"=>22,"性别"=>"女") ); foreach ($array as $val){ // 遍历数组 foreach ($val as $K=>$v){ //输出数组元素 echo $K."=>".$v."<br>"; } echo "<br>"; } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Which methods in php can output all elements of an array?. For more information, please follow other related articles on the PHP Chinese website!