Learn
Ordered Arrays
Printing Arrays

Since arrays are a more complicated data type than strings or integers, printing them is slightly more challenging. Using echo won’t have the desired result:

$number_array = [0, 1, 2]; echo $number_array; // Prints: Array

When we tried to use echo to print $number_array, it printed the word “Array” rather than the contents of the array. To print the contents of the array, we can use PHP built-in functions. The built-in print_r() function outputs arrays in a human readable format:

print_r($number_array);

This will output the array in the following format:

Array ( [0] => 0 [1] => 1 [2] => 2 )

If we merely want to print the elements in the array listed, we can convert the array into a string using the built-in implode() function. The implode() function takes two arguments: a string to use between each element (the $glue), and the array to be joined together (the $pieces):

echo implode(", ", $number_array);

This will output in the following format:

0, 1, 2

Let’s practice printing arrays!

Instructions

1.

We’ve created a couple arrays for you. Use the echo and the implode() function to print the $message array using "!" as the $glue.

2.

Use the print_r() function to print the $favorite_nums array.

Folder Icon

Take this course for free

Already have an account?