Detailed Guide On Arrays In PHP

Good Day!

Here is yet another article of Fast PHP Articles Series. Today we are going to discuss ARRAYS. We will learn its syntax, its different types, the different built-in array functions that help to perform different tasks related to arrays quickly and different practical examples explaining the use of arrays in PHP.

By the end of this article you should be able to:

- Define Arrays
- Use different types of Arrays
- Use different Built-in functions related to Arrays e.g list(), each(), var_dump, print_r, var_export()

- Write basic as well as complex php code using Arrays.
- Working with multidimensional arrays
- Understanding Foreach loop with the help of different examples

But before we discuss arrays let me tell you a very interesting story.

I have a DVD shop near my office that keep a very good collection of English movies. You can find movies on almost all genres e.g action movies, horror movies, romantic movies (hhhhh - ‘deep breath’), dramas, stage plays, religious movies and so on….

The shop-owner is not a very educated person but still he is able to manage the 20,000 plus DVDs very easily and he can take out the movie as soon as you say its name… hmm, the point is that how does he do that?

Well, I have analyzed his strategy and let me disclose this big secret to oraganize bunch of items with a special method to handle them easily.

He has categorized all the DVDs into different genres as we discussed above and also has given special IDs / codes / numbers to different shelves in his shop. He keeps the related movies in the same shelves. Each shelf is labeled after the category name e.g Romantic Movies, Horror Movies etc etc… Each DVD has a unique ID that can be used to track that DVD.

When a customer asks for a movie say Double Team, he quickly moves to the shelf labeled as Action Movies, then to the ROW labled as ‘D’ which means movies names starting with ‘D’ and then quickly reaches to the sequence of ‘D’ followed by ‘O’ and gets to the DOUBLE TEAM movie. And he memorizes the IDs of famous DVDs so when you ask him he will tell you pick the DVD # xxxx from shelf labeled by THIS NAME and you can directly pick it from there.

And all this is done so quickly that it seems like magic to get a specific DVD from a huge collection so quickly. So if you ever start to run a DVD shop then do the following to ORGANIZE YOUR DVDs:

a) Keep the similar DVDs in the same shelf.
b) Label each Category by its name.
c) Label ROWS of DVDs.
d) Assign IDs to all DVDs .

Let’s mug the moral of this story and move back to the computer world.

In programming sometimes you have to handle with different related values which are bound together in different ways. For example Names Of Top Five Students, Models Of Porsche Cars, Variables Submitted From A Form and so on. In such conditions you need to organize your code and logic to handle similar type of data efficiently and quickly. For this purpose you can use the logic of DVDs seller by:

1) Organizing Data into different bounded-together categories.
2) Laealing the ROWS.
3) Assigning Unique IDs to each data value.

There could be different techniques to do this and one of them is ARRAYS.

Raw Definition Of Arrays: A box that helps you to keep the similar data / data of same interest together for better organizing and processing

Proper Array Definition:

“Collection of different variables under the same label to keep values organized and easily accessible for processing”

Yeah, it’s my own definition of arrays and I keep the right to define anything in my own words as long as the core concept is correct and you can understand what I am talking about.

Though some also define arrays as “it’s kind of variable that contains more variables in itself”.

Please remember that PHP handles normal variables and arrays in a slightly different way.

Array Syntax:

$arrayName = array (”value1?,”value2?,”value3?);

We use $ sign to give an array name like we do for variables, after that an equal sign and then keyword ‘array’ that tells the parser that we are working with arrays and then different values within parenthesis and each value enclosed in double quotes separated by comma.

PHP Example to define and print arrays:

$Top3Sites = array ("","","");

The output of the above programme will be.

[0] =>
[1] =>
[2] =>

Please note that we use print_r to print an array because you cannot print an array with echo or print function (both are used to display output) though you can use echo or print to display single items from the array e.g.:

echo $Top3Sites[0]; //

Remember that the index number starts from 0 and not 1.

Each value of the array get a unique ID which is known as INDEX NUMBER.

The other way could be to define three different variables and then assign them values and use different statements to display them. It could be acceptable in case of three values for the sake of argument though will be rejected when we are dealing with fifty or hundred values.

So arrays are more organized and can serve to collect the different values under the same label for quick processing.

In the above example we defined and assigned values to the array in a single step though you can also do it as follows:

$students = array(); //just define an array

//assigning values

$students[0] = "Haroon";
$students[1] = "Celine";
$students[3] = "Jennifer";
$students[4] = "Bobby";


Types Of Arrays:

There are three different types of arrays in PHP:

a) Numeric Array: An array with a numeric ID key.
b) Associative Array: An array where each ID key is associated with a value.
c) Multidimensional Array: An array containing one or more arrays.

Now lets discuss different types of arrays in details.

Numeric Arrays: Numeric arrays use integer / numbers as their index number to identify each item of the array. The example we discussed above are numeric arrays as they have integer values as index numbers for each item.

$colours = array("white","black","blue");


output will be

[0] => white
[1] => black
[2] => blue

In the above output you can see the index numbers for white, black and blue are 0,1,2 respectively which are numeric values and hence we call such arrays numeric arrays.

Associative Arrays:

Sometimes it’s better to use the index name instead of index number for example if you want to save three students' names and numbers so your best option will be to use each student’s name as index value for the array and his numbers as the values, behold on the example below,

$students['Anna'] = 90;
$students['Maria'] = 60;
$students['Jennifer'] = 40;

When you submit a form using POST or GET method you get a similar associative array on the receiving page that contains the name of each form field as array index and its value as index value. Try to make a HTML form with some fields and post it and on the receiving page print the global arrays like


and you will see the associative array.

Associative Arrays are more easy to handle and to process information especially dealing with complex form submission and dynamic values from database etc.

Multidimensional Arrays:

A multidimensional array can contain arrays within itself and the sub arrays contain more arrays within them.

Let's move to a real world example to understand the concept of multidimensional arrays:

David has two sons Richie and Mason. Richie has two daugters Sue and Natasha while Mason has three daughters Nichole, Salma and Amber.

Now they family tree is as follows:

mutidimensional arrays

If we want to display David’s family tree with a multidimensional array in PHP then we can define an array as below:

$david = array



This is how you can use multidimensional arrays to organize data. Try to submit an array of form fields and then print the global array to check the output, you will get the global array as multidimensional array that will contain more sub arrays.

FOREACH LOOP: If you remember in my last article about “Loops In PHP” I had left the FOREACH LOOP to be discussed later and now the time has come to discuss it.

Foreach loop is used for arrays to take each next value from array and perform whatever action is required on it.

The basic syntax of a foreach loop is as below:


foreach ( $arrayname as $temporaryVarName ) {

// foreach loop body
//$temporaryVarName holds the array values and
//on each loop-run it will pick the next available value from the array

Let’s write a programme using a foreach loop to understand its working in depth:

  $students = array(); // define array students
//assigning values
    $students[0] = "david";
      $students[1] = "kevin";
      $students[2] = "julie";
    $students[3] = "nayyar";
  now we will use the foreach loop to display all the students names i.e the array values in one go
foreach ( $students as $std_name ) {
   echo $std_name . "\n";


In the above code the $std_name works as a temporary variable to get each value of array. On every loop-run the next available value of the array overwrite the existing value of the $std_name and then $std_namepoints to the current fetched value. So it’s just like walking through your array values one by one.

The output of the above code will be:


as we are using \n (line feed) to display each name on the next line.

The foreach loop terminates when there is no value available next that is it reaches the last value of the array which is NAYYAR in our case.

You can break the loop anytime using break statement if required (we have discussed break statement in the DECISION MAKING USING SWITCH IN PHP).

For example if you want to break the loop if the name is julie then you can include an IF statement in the above code as below:

foreach ( $students as $std_name ) {
    if($std_name == "julie") break;
    echo $std_name . "\n";


We have some other very handy functions that can work with arrays to give you the fast processing of arrays to provide efficient results. A few of them are discussed below:

Important Array Functions:

1) Save print_r function’s output: we have previously used print_r to display the array values, though we can add an extra argument to print_r and save its output to a variable e.g.:

    $myarray = array("Apples", "Oranges", "Pears");
      $output = print_r($myarray, true);
    print $output;

The print_r will display the array itself if you will not use TRUE - the second argument however it will store its output in the variable if the TRUE is provided.

2) How to find the size of an Array? Size of an array means how many values an array contains… if you want to find the number of values of an array you can use the COUNT function as follows:

    $myarray = array("Apples", "Oranges", "Pears");
    $size = count($myarray);  
    print $size; // 3

The above programme will display 3 because we have three elements in the array.

3) var_dump Function:

There is a similar function to print_r(), which is var_dump(). It does largely the same thing, but

a) prints out sizes of variables,
b) does not print out non-public data in objects, and
c) does not have the option to pass a second parameter to return its output.

For example, altering the first script to use var_dump() rather than print_r() would give the following output:

array(3) {
string(6) “Apples”
string(7) “Oranges”
string(5) “Pears”

In there you can see var_dump() has told us that the array has three values, and also prints out the lengths of each of the strings. For teaching purposes, var_dump() is better as it shows the variable sizes, however you will probably want to use print_r() in your own work.

4) var_export Function:

Also, there is the function var_export(), which is similar to both var_dump() and print_r(). The key difference with var_export(), however, is that it prints out variable information in a style that can be used as PHP code. For example, if we had use var_export() instead of print_r() in the test script, it would have output the following:

array (
0 => ‘Apples’,
1 => ‘Oranges’,
2 => ‘Pears’,

Note there is an extra comma after the last element, however this is ignored by PHP and you can copy and paste that information directly into your own scripts, like this:

    $foo = array (
    0 => 'Apples',
    1 => 'Oranges',
    2 => 'Pears',

5) array_shift Function:

The array_shift function removes the first element of an array from the array and stores it in the receiving variable.

For example if I want to remove Apples from the array used in previous programmes and store it in a different variable then I can write a programme as below:

    $myarray = array("Apples", "Oranges", "Pears");
    $fruit = array_shift($myarray);  
    echo $fruit; // Apples
    print_r($myarray);  // Oranges and Pears will be displayed without Apples

It is a very handy function if you have a multidimensional array posted from a form and you want to fetch the sub-array from the main array. But remember when you fetch out a sub-array from the main array using array_shift then the receiving variables ($fruit in previous) will not be a normal variable but an array.

I will also suggest you to study three other useful functions related to array_shift on PHP Official Manual at


PHP offers a very long list of different useful array functions that you can find at PHP OFFICIAL MANUAL.

One thing I want to mention here is that the foreach loop is not the only way to process arrays - you can do it using other loops e.g FOR LOOP or list() and each() functions.

To process an array through you will need to find the total number of the values in the array, i.e the size of array as below:

    for ($i = 0; $i < count($array); ++$i) {
        print $array[$i];

This will work fine for numeric arrays which have integer values as index-numbers but this doesn’t fit associative arrays.

Process Arrays with LIST() function:

PHP offers the LIST() function that can be used to go through array values easily and quickly as below:

    while (list($var, $val) = each($array)) {
        print "$var is $val\n";

List() is a function that does the opposite of array() - it takes an array, and converts it into individual variables. Each() takes an array as its parameter, and returns the current key and value in that array before advancing the array cursor. “Array cursor” is the technical term for the element of an array that is currently being read. All arrays have a cursor, and you can freely move it around - it is used in the while loop above, where we need to iterate through an array. To start with, each() will return the first element, then the second element, then the third, and so on, until it finds there are no elements left, in which case it will return false and end the loop.

The meaning of that first line is “get the current element in the array, and assign its key to $var and its value to $val, then advance the array cursor".

Get both index and value of array element: If you want to read the index-name as well as its value for each array element then you can use foreach loop as follows:

foreach ($array as $key => $val) {
    print "$key = $val\n";

It is very handy when you deal with associative arrays.

Arrays are a very deep topic and it has a lot more to discuss and even I can easily write a complete book on arrays only. But the aim of this article is to give you very sound understanding of arrays and different methods to store and process information in arrays. However if you have any specific question about arrays please feel free to email me or comment on this article.

It’s a long article so there could be a few typos if you find any please report to me so that I can fix it. Till we meet again keep practicing and take care…

- Haroon Ahmad

FAST PHP Tutorial (Part 1)
How to Install PHP on Windows (Fast PHP Tutorial Part 2)
How To Install PHP On Linux
How To Install Apache on Windows
Easy Installers to Install PHP, MySQL, Apache on Windows
PHP Programming Basics
Operators in PHP
Decision Making using IF-ELSE in php
Decision Making using PHP Switch Statement
Loops In PHP

Share this page:

8 Comment(s)

Add comment



well explained..


    nice stiffs.  begineer like me can go through easily.

You may also check php manual...

From: Anand Kumar


It is really very helpful. It is very orderly precise and helpful to the beginners.

From: Anonymous

really commendable ...well organized and comprehendable

thanks a lot may god bless you

From: Anonymous

it is nice and easy one

From: RearViewMirror

thanks a lot sir, it's been a month , at last I've found something as easy as this , thank you for taking your time to do this , thank you thank you 

From: akshay


From: waseem

thaks a -lak-laka-laka-lotttt....

god bless you bro :)