In PHP, array is a common data type. If you want to output array elements, there are several ways to do it.
The print_r() function is a very commonly used function in PHP and is used to output the value of a variable. It can output all elements of the array and their key names. To use this function, just pass an array to it as a parameter. For example:
$array = array('foo', 'bar', 'baz'); print_r($array);
The above code will output:
Array ( [0] => foo [1] => bar [2] => baz )
Among them, Array is the identifier of the array type, the number in square brackets is the key name corresponding to the array element, and the arrow is followed by the array element. value.
The var_dump() function can also output all elements of the array and their key names, and compared with the print_r() function, it also Able to output information such as the type and length of array elements. To use this function, just pass an array to it as a parameter. For example:
$array = array('foo', 'bar', 'baz'); var_dump($array);
The above code will output:
array(3) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" }
Among them, array(3) means that the number of array elements is 3. The number in the square brackets is the key name corresponding to the array element, and behind the arrow is the value and type of the array element.
The foreach loop is a common way to traverse array elements in PHP. To use this loop, just pass it the array as a parameter and then use a temporary variable to receive the value of each element. For example:
$array = array('foo', 'bar', 'baz'); foreach ($array as $item) { echo $item . '<br>'; }
The above code will output:
foo bar baz
The for loop in php can also be used to output array elements. To use this loop, you only need to use the key names of the array elements to loop. For example:
$array = array('foo', 'bar', 'baz'); for ($i = 0; $i < count($array); $i++) { echo $array[$i] . '<br>'; }
The above code will output:
foo bar baz
The above are several ways to output array elements in PHP. While each method has its own pros and cons, both work well for different output needs.
The above is the detailed content of How to output array elements in php. For more information, please follow other related articles on the PHP Chinese website!