Array output with print_r()
Learn to print an array's contents in a readable form with print_r().
The print_r() function
To see the full contents of an array in a readable form, use print_r(). You write the array name inside parentheses: print_r($scores);.
The output shows each element's index and value as [0] => 85. This is ideal for debugging when you want to quickly see what an array holds. echo cannot print an array directly, so print_r is preferred.
The second parameter: return
By default print_r prints its result to the screen. If you pass true as the second parameter, it does not print; instead it returns the result as a string.
For example, $text = print_r($scores, true); does not write to the screen; it puts the output into $text. This is useful when you want to process the output later (for example to write it to a file or log). On web pages, wrapping inside a <pre> tag improves readability.
Exercise Print the array with print_r
Print the $scores = [85, 92, 78]; array with print_r. Expected output: an Array header, parentheses, and the index and value of each element.
Show example solution
<?php
$scores = [85, 92, 78];
// Print the array with print_r
print_r($scores);
Example solution:
<?php
$scores = [85, 92, 78];
// Print the array with print_r
print_r($scores);
Test yourself
-
What does the output of print_r([10, 20, 30]); look like?
print_r([10, 20, 30]);- Array ( [0] => 10 [1] => 20 [2] => 30 )
- Array ( [0] = 10 [1] = 20 [2] = 30 )
- 10 20 30
- [10, 20, 30]
Show answer
Array ( [0] => 10 [1] => 20 [2] => 30 ) — Correct. print_r starts with Array and shows index and value of each element.
-
Complete the print_r call
$scores = [85, 92, 78]; ____;Show answer
$scores = [85, 92, 78]; print_r($scores); -
Match each function to its use
- print_r
- Prints an array readable
- echo
- Prints a single value
- var_dump
- Gives type and value
-
Which is the right choice to print an array to the screen?
- echo $scores;
- echo $scores[0];
- count($scores);
- print_r($scores);
Show answer
print_r($scores); — Correct. To see the full contents of an array, use print_r($scores);.