Home > PHP, PHP Tutorials > PHP5 Tutorial on Arrays

PHP5 Tutorial on Arrays

October 31st, 2007 admin Leave a comment Go to comments

This PHP5 tutorial discusses about PHP arrays.

What is an array?
Generally speaking an array is continuous allocation of memory of similar data types.

This means that you can define a single array variable which can hold multiple values at the same time. These multiple values are retrieved using an index number. Don’t worry if you did not get this… more explanation ahead.




The same definition mentioned above is also applicable for PHP as well, with an exception that it can store data of different data types in one array.

Memory representation of an array

array.gif

In the above diagram, you can see that variable $a has been allocated 5 slots of memory in which data can be stored. Each of these slots / boxes are referred using an index number that starts from 0. A common mistake for people learning arrays is to consider the starting position of an array as 1.

Remember a rule of thumb, if an array has 5 elements then the starting index of the array is from 0 (always) and the ending index number 5 – 1, i.e. 4.

Declaring an PHP array

$a = array(); // this line creates an array by the name $a
$a = array(1,2,3); //an array declared and initialized with integer values
$a = array(‘name’ => ‘sunil’, ‘email’ => ‘[email protected]’); // an associative array

PHP Array manipulation

You can store and retrieve values from an array during program execution as follows:

a. this assigns/overwrites the value stored in the first element of array $a
$a[0] = 10;

b. this assigns/overwrites the value stored in the sixth element of array $a
$a[5] = 20;

c. this assigns/overwrites the value in the last element of array $a
$a[count($a) - 1] = 100;

You will learn more about the count() function in a while.

Types of arrays in PHP

You can declare 2 types of arrays in PHP.

a. Index based arrays
An index based array will be manipulated using an index number, like $a[0], $a[2], etc.

b. Associative arrays
An associative array will be manipulated using keys, like $a['name'], $a['email'];

Traversing an array
Traversing an array means the logic to visit each and every element of an array using a looping structure like while() and for(,,).

a. Traversing index based arrays

<?php

$a = array(10,20,30);

for($i = 0 ; $i < count($a) ; $i++) {
echo $a[$i] . “\n”;
}

?>

Output:
1
2
3

In the above example, we use a for() looping structure to traverse all the elements of the array. count() is an array function which returns the count of number of elements in the array $a, which in our case is 3.

The reason why we subtract 1 from count(), i.e. count($a) – 1; is because the index of the last element is always N – 1. N in this case is 3.




b. Traversing an associative array

Traversing an associative array is a little different from traversing a index based array. The difference is that an associative array does not have index. It uses a key/value pair for storage.

<?php

$a = array(‘name’ => ‘sunil’, ‘email’ => ‘[email protected]’); // an associative array

foreach($a as $key => $value) {
echo $key . ” : ” . $value . “\n”;
}

?>

Output:
name : sunil
email : [email protected]

In the above example, the key and value of each element of array $a is stored in $key and $value respectively. After the first iteration, $key contains ‘name’ and $value contains ‘sunil’

Multi-dimension Array

A multi-dimension array is an array within an array. This means that every element of a multi-dimension array is another array itself. Look at the memory representation below.

multi-dim-array.gif

Declaring a multi-dimension array

Example 1:

$multi = array(
array(1,2,3),
array(99,98,97)
);

The above is an index based multi-dimension array. Look at the diagram below.

multi-dim-array-1.gif

Example 2:

$multi = array(
‘first’ => array(1,2,3),
‘second’ => array(99,98,97),
);

The above is an associative multi-dimension array. Look at the diagram below.

multi-dim-array-2.gif

Traversing a multi-dimension array

Traversing an array means to programmatically visit each and every element of an array.

a. Traversing a index based multi-dimension array

<?php

$multi = array(
array(1,2,3),
array(99,98,97)
);

for($i = 0 ; $i < count($multi) ; $i++) {
for($j = 0 ; $j < count($multi[$i]) ; $j++) {
echo $multi[$i][$j] . ” “;
}
echo “\n”;
}

?>

Output:
1 2 3
99 98 97

b. Traversing an associative multi-dimension array

<?php

$multi = array(
‘first’ => array(1,2,3),
‘second’ => array(45, 67, 98)
);

foreach($multi as $key => $value) {
echo $key . ” : “;
for($j = 0 ; $j < count($multi[$key]) ; $j++) {
echo $multi[$key][$j] . ” “;
}
echo “\n”;
}

?>

Output:
first : 1 2 3
second : 45 67 98

Please feel free to leave behind any comments or questions that you might have.

Related Posts

Categories: PHP, PHP Tutorials Tags:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/sunilb/www.sunilb.com/wp-content/plugins/all-in-one-seo-pack/aioseop.class.php:245) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41
  1. June 28th, 2008 at 12:02 | #1

    Good one, but plz provide us some more operations with arrays.

  2. andyman
    September 3rd, 2008 at 03:53 | #2

    This tutorial implies that it’s not possible to nest an associative array inside another associative array. I hope that’s not the case! I’m still new to PHP.

  3. omegared
    October 26th, 2008 at 12:16 | #3

    Can you have an associative array within an indexed array?

    Is it wise / possible to assign that array to a session variable?

  4. admin
    November 15th, 2008 at 19:44 | #4

    Hi Andy,

    It’s possible to have an associative array within an associative array.

    Let me know if you need anything spefic pertaining to it.

    Suniil

  5. Jonathan
    July 1st, 2009 at 00:03 | #5

    Good Description. Thanks

  6. Vindhya
    October 13th, 2009 at 09:17 | #6

    Hi,

    I ve doubt in multi dimension array..

    By default, the values are stored in row wise..

    Is it possible to store it in column wise ??

    If so, how is it possible ??

    Also how to perform the matrix operartion using multi dimension array ??

    Pleaz provide me the code with explanation ..

    Thank You

  7. admin
    October 13th, 2009 at 12:36 | #7

    Hi Vindhya,

    It is not possible to store it the other way round as you have asked. Array manipulation is always done in the manner explained in this article – which is generic across any programming language.

    I am afraid you will have to develop the matrix logic yourself… however I can evaluate your program and guide you develop it… as this is the only way to build programming logic.

    Regards,
    Suniil

  1. November 20th, 2007 at 01:46 | #1
Enter this code to leave comment (Sorry, but bots get me crazy :) )