How to print the contents of an array in php

PHPz
Release: 2023-04-25 09:45:43
Original
911 people have browsed it

In PHP, we often need to print the contents of an array to facilitate debugging and viewing the specific information of the array. In this article, we will introduce several ways to print arrays in PHP.

Method 1: print_r function

The print_r function is one of the most commonly used methods to print arrays in PHP. It prints all dimensions of the array recursively and the output is easy to read. For example:

Copy after login

Run the above code, the output result is as follows:

Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => a [1] => b [2] => c ) )
Copy after login

This result tells us that the array contains three elements, the first element is the number 1, and the second element is Number 2, the third element is an array containing three elements.

Method 2: var_dump function

The var_dump function is also one of the commonly used methods to print arrays in PHP. It will print out the detailed structure information of the array, including the type, length and value of each element. For example:

Copy after login

Run the above code, the output result is as follows:

array(3) { [0]=> int(1) [1]=> int(2) [2]=> array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } }
Copy after login

This result tells us that the array contains three elements, and the type of the first and second elements is integer. The type of the third element is an array. The array contains three elements, and the type of each element is a string, namely a, b, and c.

Method 3: foreach loop

In addition to using the function to print the array, we can also use the foreach loop to traverse the array and print out the value of each element. For example:

Copy after login

Run the above code, the output result is as follows:

1 2 a b c
Copy after login

This result tells us that the array contains three elements, first print the values of the first and second elements, Then when the third element is encountered, an inner loop is executed to print out the value of each child element.

Through the above three methods, we can easily print out the array in PHP to facilitate debugging and viewing during our development process.

The above is the detailed content of How to print the contents of an array in php. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!