Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create dynamic Arrays and display them using PHP

In this article we will see how we can create dynamic arrays in PHP, display the same and also learn on the multidimensional array.

Arrays are special data types. Despite of other normal variables an array can store more than one value. Let's suppose you want to store basic colors in your PHP script. You can construct a small list from them like this:

Color list:

  • red
  • green
  • blue
  • black
  • white

It is a bad idea to store each color in a separate variable. It would be very nice to have the above representation almost as it is in PHP. And here comes array into play.

The array type exists exactly for such purposes. So let's see how to create dynamic array to store our color list.

There are more ways to create dynamic arrays in PHP. Maybe the easiest way to create our color list array is the following:

Listing1: Code with the color list array:

$colorList = array("red","green","blue","black","white");

And other solution is to initialise array elements one-by-one as follows:

Listing2: Initialising the array elements:

$colorList[0] = "red";
$colorList[1] = "green";
$colorList[2] = "blue";
$colorList[3] = "black";
$colorList[4] = "white";

If you don't want to bother about numbering, you can create your array as this:

Listing3: Creating array without numbering

$colorList[] = "red";
$colorList[] = "green";
$colorList[] = "blue";
$colorList[] = "black";
$colorList[] = "white";

As you can see this is almost similar to the other but here we didn't write any number between the square brackets. In this case PHP makes the numbering internally from 0 to 4. This function is the so called auto-incremented keys.

Step 3 - Display the array content

In the last step we have created an array. It is not important which solution 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 element. 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:

Listing4: Code to display one element of the array

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:

Listing5: Code to display all the elements in the array

for ($i=0;$i<=4;$i++){
echo $colorList[$i];
}

It is quite easy. However it is not the best solution 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 for each loop as this:

Listing6: Using the for loop

foreach ($colorList as $value) {
echo $value;
}

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 display that array as key-value pairs. Besides this var_dump also displays variable informations. You can use them as follows:

Listing7: Using print_r and var_dump functions:

print_r($colorList);
echo "";
var_dump($colorList);

Step 4 - Associative arrays

In general PHP arrays are maps, which mean that it is a type that maps values tokens. In our example it means that where the key is 0 there the value is "red" and where the key is 1 there the value is "green". However you have the possibility to use more meaningful keys. Associative array means that you can assign an arbitrary key to every value. Associative arrays are sometimes referred to as dictionaries. Our color List array can be defined as associative array like this:

Listing8: Defining an associated array

$colorList = array("apple"=>"red",
 "grass"=>"green",
 "sky"=>"blue",
 "night"=>"black",
 "wall"=>"white");

You have to remember that array keys are case-sensitive, but type insensitive. It means that 'a' differs from 'A' but '1' is the same as 1.

So, the array above can be defined (created) one-by-one elements like this:

Listing9: Defining array by one-by-one elements

$colorList["apple"] = "red";
$colorList["grass"] = "green";
$colorList["sky"]   = "blue";
$colorList["night"] = "black";
$colorList["wall"]  = "white";

And you can display the content similar to the normal array, but here you need to use the string value instead of the number.

Listing10: Using the string value

echo "The sky is ".$colorList["sky"]
" and the grass is ".$colorList["grass"];

You can mix your array and use numbers and strings in the same list like this:

Listing11: Using Numbers and Strings

$colorList["apple"] = "red";
$colorList[5]       = "green";
$colorList["sky"]   = "blue";
$colorList["night"] = "black";
$colorList[22]      = "white";

As you can see even the numbers can be any so you don't have to make it continuous. However be aware of using such mixed arrays as it can result errors.

Step 5 - Multidimensional arrays

As each element value of the array can be any type it means that it can be other array as well. If an array element value is another array then this is a multidimensional array. Of course the internal array values can be arrays as well and so on. You can define 10 dimensional (or more) array if you want.

Creating a multidimensional array is as almost simple as the normal array. Let's see an example:

Listing12: Creating the Multidimensional array

$myLists['colors'] = array("apple"=>"red",
 "grass"=>"green",
 "sky"=>"blue",
 "night"=>"black",
 "wall"=>"white");                      
$myLists['cars'] = array("BMW"=>"M6",
 "Mercedes"=>"E 270 CDI",
 "Lexus"=>"IS 220d",
 "Mazda"=>"6",
"Toyota"=>"Avensis");     

To access and display an element in the multidimensional array you just extend the key list as follows:

Listing13: Accessing the multidimensional array

echo $myLists['cars']['Toyota'];

Of course you can define normal, mixed and associative multidimensional arrays.

Step 6- Array functions

And last you sometimes want to sort your array for example to display its content in alphabetical order. To do this you have more possibilities. There is more built in array sorting functions in PHP. The most known are sort and asort.

The difference between them is that sort renumbers the keys so you will lose the key values. So if you need the key names (associative arrays) use the asort function.

You can use them as follows:

Listing14: Using sort and asort functions

asort($colorList);
sort($colorList);

Both of the functions sorts values in ascending order. If you want to sort them descending use the corresponding rsort and arsort functions.

Hope you liked the article, see you next time.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login