1. Using print_r() function
The most common method to lớn print the contents of an array is using the print_r() function, which displays the human information about a variable. For an array, the values are displayed in a format that shows keys và elements.
Bạn đang xem: Print an array in php
The following code demonstrates this by printing an associative array using the print_r() function.
Note that you can capture the output đầu ra of the print_r() function by setting the second parameter khổng lồ true. Now the print_r() function will return the output rather than printing it.
2. Using var_export() function
The var_export() function outputs or returns a parsable string representation of a variable, which is valid PHP code. It is often used by programmers lớn print an array in PHP.
3. Using var_dump() function
Another good solution lớn dump information about the contents of an array is using the var_dump() function. For an array, it recursively displays structured information about it such as its data type, value, and length.
The following code demonstrates this:
4. Using json_encode() function
The json_encode() function returns a string containing the JSON representation of a value. It can be used khổng lồ encode an array in PHP, resulting in a human-readable JSON string.
Here’s how the output would look lượt thích for an associative array,
5. Using foreach construct
Finally, you can use the foreach construct lớn iterate over arrays.
The following code demonstrates this, where it assigns the value of the current element to $value on each iteration:
The following code additionally assigns the current element’s key lớn the $key variable on each iteration.
Note: The whitespace is not preserved in the DOM, rather a single space is rendered in a browser. The solution is khổng lồ wrap the output đầu ra of the above functions inside a tag.
That’s all about printing an array in PHP.
Average rating 4.88/5. Vote count: 42
No votes so far! Be the first lớn rate this post.