What is PHP?
What is an array in PHP?
An array in PHP is a variable used to store data containing various elements. The elements of an array are identified by a unique key/index, which can be a number or a string. PHP has two types of arrays: indexed arrays and associative arrays. PHP provides many built-in functions for working with arrays, including sorting, searching, splitting a string to array, getting the length of an array, converting an array to JSON, and converting an array to string.
How to print an array in PHP?
To print an array in PHP, you can use the built-in print_r() function, which prints or displays information about a variable, including its type and value.
- variable: specifies the array about which we want to get information
- return (Optional): when set to "True", this function will return information, but not print it. The default value is "False".
PHP Print Array Examples
The following are examples of printing an array in PHP:
Displaying information about an array using var_dump()
To display information about an array in PHP, you can use the var_dump() function, which dumps structured information such as the type and value of a given variable. Arrays and objects are explored recursively with indented values to show structure.
- variable: defines an array to display information
Printing the elements of an array using a foreach loop
In some cases, you may want to display additional (for example, dynamically calculated) information about the elements of an array in PHP. In such a case, you can use a foreach loop, which provides a simple iteration of the elements of an array.
Printing the elements of an array using the implode()
The following is an example of printing an array using the implode() function. The implode() function concatenates array elements into a string.