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 DVDs shop near my office that keep a very good collection of English Movies. You can find movies on almost all genre e.g Action Movies, Horror Movies, Romantic Movies (hhhhh - ‘deep breath’), Dramas, Stage Plays, Relegious 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 genre 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 labled 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 labled 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 Labeld 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 starts DVDs 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 Porche 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) Labaling the ROWS
3) Assigning Unique IDs to each data value

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

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:


<?php
 
$Top3Sites = array ("fastcreators.com","howtoforge.com","scriptsbible.com");
 
print_r($Top3Sites);
</a>
?>

the output of the above programme will be

Array
(
[0] => fastcreators.com
[1] => howtoforge.com
[2] => scriptsbible.com
)

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 item from the array e.g

echo $Top3Sites[0]; //fastcreators.com

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 following


<?php
$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 number for each item.

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

print_r($colours);

//output will be

Array
(
[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 name 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,


<?php
 
$students['Anna'] = 90;
$students['Maria'] = 60;
$students['Jennifer'] = 40;
 
?>

When you submit a form using POST or GET method you get similar Associate 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

print_r($_POST);
print_r($_GET);

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

Lets move to a real world example to understand the concept of multidimensional array;

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 follow


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
(
“richie”=>array
(
“Sue”,
“Natasha”
),

“Mason”=>array
(
“Nichole”,
“Salma”,
“Amber”
)

);

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 Foreach Loop is as below,

FOREACH Syntax:

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 foreach loop to understand its working in depth,


<?php
 
  $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_name points 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,

david
kevin
julie
nayyar

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


 
<?php
 
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


<?php
    $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 that how many values an array contains… if you want to find the number of values of an array you can use COUNT function as follow,


<?php
    $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) {
[0]=>
string(6) “Apples”
[1]=>
string(7) “Oranges”
[2]=>
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:


<?php
    $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 store 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,


<?php
 
    $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 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

array_unshift
array_pop
array_push

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 it’s not 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,


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

this will work fine for Numeric Arrays which have integer value as index-number but this doesn’t fit Associative arrays.

Process Arrays with LIST() function:

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


<?php
    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 follow,


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

it is very handy when you deal with Associate arrays.

Array is 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

Other Articles Of This Series:

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

3 Comments

  1. kenman said,

    February 10, 2007 at 5:45 am

    finally…

    for ($i = 0; $i &lt; count($array); ++$i) {
        print $array[$i];
    }

    Two quick suggestions…

    1) echo is faster than print.

    2) “$i < count($array)” will recount the size of the array on each iteration, which will get exponentially worse the larger the array is that you’re working with. Instead, use:

    for ($i = 0, $cnt = count($array); $i &lt; $cnt; ++$i)

    Otherwise, nice primer on arrays!

  2. haroon.ahmad said,

    February 10, 2007 at 10:12 am

    good point kenman, it is better to count the array rather than counting it in every loop run THOUGH i had given example according to my array size in the article which is small :) .. but still very good point and readers must take this under consideration.

  3. Glacier said,

    August 4, 2008 at 10:09 pm

    i read your article..the things you have written sound very sincere and nice topics i am looking forward to its continuation.

Post a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word