PHP is a commonly used programming language, in which arrays are a frequently used data type. An array is a very convenient data structure that can be used to store multiple values that can be accessed through indexes. In PHP, array output is a very important and common operation.
1. Output the array in the specified format
In PHP, we can use the array() function to create an array. Then, we can use echo or print statements to output the array to the browser. However, the array output in this way is not a good-looking format, and it is very unintuitive for large arrays.
In order to better output the array, we can use the print_r() or var_dump() function. These two functions can output arrays to the screen in a more concise way.
The usage of print_r() function is as follows:
The output result is as follows:
Array ( [0] => Foo [1] => Bar [2] => Baz )
The usage of var_dump() function is as follows:
The output result is as follows :
array(3) { [0]=> string(3) "Foo" [1]=> string(3) "Bar" [2]=> string(3) "Baz" }
2. Use foreach() loop to output array
In addition to using print_r() or var_dump() function, we can also use foreach() loop structure to output array. The following is an example of a simple foreach() loop structure:
"张三", "年龄" => 20, "职业" => "程序员"); foreach ($arr as $key => $value) { echo "{$key}: {$value}
"; } ?>
The output result is as follows:
姓名: 张三 年龄: 20 职业: 程序员
The foreach() loop can loop from the first element according to the index until the array The last element. In the loop, we use the key => value format to output the keys and values of the array one by one.
3. Use the implode() function to convert an array into a string
In some cases, we need to convert an array containing multiple elements into a string. At this time, we can use the implode() function. The implode() function can concatenate all elements of an array into a string, where each element is separated by the specified delimiter.
The following is a sample code:
The output results are as follows:
a,b,c,d
Summary:
The above introduces several ways to output arrays in PHP functions Methods, including outputting arrays in a specified format, using the foreach() loop structure to output arrays, and using the implode() function to convert arrays to strings. For PHP programming beginners, these methods are very practical and help to improve the efficiency and readability of the code.
The above is the detailed content of How to output an array in php (4 methods). For more information, please follow other related articles on the PHP Chinese website!