PHP Array tutorial - Display the array content

Home - Tutorials - Basics

In this tutorial I will show you how to work with arrays in PHP. You will learn how to create, sort or print an array. Besides this we will touch on multidimensional arrays as well.

Tutorial info:

Name:PHP Array tutorial
Total steps:7

Bookmark PHP Array tutorial

Step 3 - Display the array content

PHP Array tutorial

In the last step we have created an array. It is not important which sollution you choose the result is the same. It's nice but how you can use the data in the array. For example how to display the elements? There are more ways to do this. Let's see the possibilities.

If you want only display one element of the array then you can just write the following code:

  1. echo $colorList[0];
This code will display the text "red". However you may want to display all elements in the array. You can write a loop and display them like this:
  1. for ($i=0;$i<=4;$i++){
  2. echo $colorList[$i];
  3. }
It is quite easy. However it is not the best sollution as the number of element is hard coded. There is a much better way to display all elements of an array. You can use a foreach loop as this:
  1. foreach ($colorList as $value) {
  2. echo $value;
  3. }
If you want to display array content for debugging purposes then you can use 2 built in PHP functions. These are the print_r and var_dump. These functions displays tha array as key-value pairs. Besides this var_dump also displays variable informations. You can use them as follows:
  1. print_r($colorList);
  2. echo "";
  3. var_dump($colorList);

In the next step we will learn about associative arrays.

Previous Step of PHP Array tutorialNext Step of PHP Array tutorial

Tags: array, php array, sort array, create array, print array, array length

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.1331