8 Array

Hiren Joshi

epgp books

 

 

 

Introduction:

 

Let us assume, you want to store name of five students. You can define five variables. Suppose that there 50 students now available. So you have to code 50 variables. To manage 50 variables is indeed cumbersome and error to prone task. Instead you can create an array.

 

Array is a data type in PHP. Array is a data type which can store multiple items of same data type or different data types. The item in array is known as element. Each element can store a value. To get the value of a particular element of an array, an index is used. In short, array element has index and value. The data type of an index can be either integer or string. The value of an item can be any PHP data type. By Default the data type of index is integer in PHP.

 

You can create array by single statement of multiple statements as per your requirement. Both are the valid way to create an array.

 

1.Create array using single statement$arrayname = array(value1, value2 [, value3,….]);

2.Create array using multiple statements

a. $arrayname = array( );

b. $araryname[index] = value;

 

Let us take an example, to create an array:

 

$name = array( );

$name[0] = ‘Hiren’;

$name[1] = ‘Jignesh’;

$name[2] = ‘Vimal’;

 

// Or you can write

 

$names = array(‘Vipul’,’Chetan’,’Mihir’);

 

In array, element index starts with 0. The index for second element is 1 and so on.

 

So, vipul is stored at index 0 in array $names. Mihir is stored at index 2 in array $names. To retrieve , particular element from array type the arrayname with its index. For example, echo “<br> $names[1]”;will display Chetan on your browser.

  To add an element at the end of an array, the syntax is

 

$arrayname [ ] = value

In case you code

$names[ ] = “Gautam”;

 

Then $names array has 4 elements : ‘Vipul’,’Chetan’,’Mihir’, „Gautam‟ You can add element in array at specific index also.

 

$names[7] = “Jaymin”;

 

Then the array $names has total 8 elements. The element at index 4,5, and 6 has null value.To delete the value at any particular index, unset function is used. The general syntax for deleting value at any particular index is:

 

unset($arrayname[index])

To delete the value chetan from array $names, the code is unset($names[1]);

 

After unset the element 2(index 1) , the array has values Vipul Mihir Gautam Jaymin.

 

unset($names) deletes the entire array $names.

 

The array_values function is return a new array in which the gaps within an array is removed and the values are reindexed. It takes arrayname as argument.

 

$arr = array(‘one’,’two’,’three’, ‘four’);

 

unset($arr[2]);

 

$arr = array_values($arr);

 

Functions to work with array using for loop

 

 Let us understand the use of these functions by example

 

$numbers = array ( );

for($i = 1 ;$i <= 10; $i++)

{

$numbers[] = $i;

}

$num = “”;

for($i = 0; $i <count($numbers);$i++)

{

$num .= $numbers[$i] .” “;

}

echo $num;

 

The above code create an array $numbers and store 1 to 10 in it. Then using count function we restrict the loop counter and display the same array element in browser.

 

$end = end($numbers);

echo ” <br>End is : $end”;

will display

End is : 10

 

As it is the value of last element in array $numbers.

 

The code immediately after it

$key = key($numbers);

echo “<br> The current key is: $key”;

 

will display

 

The current key is: 9

 

The index 9 stores the value 10. The highest index of an array is always 1 least then the total numbers of elements in an array because the array index is begin with 0.

   Do it yourself:

 

Write a PHP code which will take an array of five number and display average value of these numbers.

 

 Foreach loop

 

The foreach loop is used for array. In foreach loop, there is no requirement of initialize a variable, test condition and increment/decrement the variable value. The general syntax of foreach loop is

 

foreach( $arrayname as [$key =>] $value)

{

Statements which are using key and value;

}

 

Let take one example of foreach loop.

 

echo “<br> For each loop for an array”;

$nums = array(1,2,3,4,5,6,7,8,9,10);

echo “<br>”;

foreach($nums as $num)

{

echo “<t> $num”;

}

 

Then the output will be

For each loop for an array

1 2 3 4 5 6 7 8 9 10

 

 

The foreach loop is used for filling gap in an array. Let us understand by one example.

 

echo “<br> For each loop for an array”;

$nums = array(1,2,3,4,5,6,7,8,9,10);

echo “<br>”;

foreach($nums as $num)

{

echo “<t> $num”;

}

unset($nums[4],$nums[5]);

echo “<br> After unset elements 5 and 6 <br>”;

foreach($nums as $num)

{

echo “<t> $num”;

}

 

Then the output will be

 

For each loop for an array

1 2 3 4 5 6 7 8 9 10

 

After unset elements 5 and 6

1 2 3 4 7 8 9 10

 

The foreach loop fills the gap as the element value 5 (index 4) and element value 6(index 5) was unset.

 

Associative array

 

String can be used as index in array in PHP. When string is used as index in array, this array is known as associative array. In associative array, the index is known as key. Similar to normal array, you can create associative array by two ways. Associative array be created by using a single statement or by using multiple statement.

 

Single statement:

 

Array ([key1 => value1, key2 => value2, key3 => value3, …])

 

Multiple statements:

 

a. $arrayname = array( );

b. $araryname[key] = value;

 

Let us understand by one simple example,

 

$statecode = array(“GJ” => “Gujarat”, “MP” => “MadhayPradesh”, “MH” => “Maharashtra”);

Following code snippet create an associative array using multiple statements:

    $countrycode = array();

$countrycode[“in”] = “India”;

$countrycode[‘ca’] = “Canada”;

$countrycode[‘fr’] = “France”;

$countrycode[‘usa’] = “America”;

 

Following code snippet create an associative array using multiple statements and display each element.

 

$countrycode = array();

$countrycode[“in”] = “India”;

$countrycode[‘ca’] = “Canada”;

$countrycode[‘fr’] = “France”;

$countrycode[‘usa’] = “America”;

foreach($countrycode as $value)

{

echo “<t> $value”;

}

 

Then the output will be

India Canada France America

To display key and value both

 

foreach($countrycode as $key => $value)

{

echo “<t> $key => $value”;

}

 

Then the output will be

 

in => India ca => Canada fr => France usa => America

   An array with integer key but keyfrite a PHP code which will take an array of five number and display average value of these numbet of as an associative array.

    $ext = array();

$ext[200] = “Vice Chancellor”;

$ext[202] = “Registrar”;

$ext[205] = “Admin”;

 

Though it is not considered a good practice, a single array can contain both integer and string indexes. For example, an array can be defined as below.

 

$emp = array();

$emp[0] = “Anil”;

$emp[1] = “Bhavin”;

$emp[2] = “Chetan”;

$emp[“senior”] = “Geeta”;

$emp[“newest”] = “Kapil”;

 

Associative works same as index array. Only the difference is here in the code, key is used instead of index.

 

In associative array, an element can be added.

 

$countrycode[‘uk’] = “United Kingdom”;

 

Will add the element with key uk and value for key is united kingdom.

 

To get the value of an array element, you can code

 

$countrycode[‘uk’]

 

If the key is not specified in an associative array, PHP uses an integer index.

 

$countrycode[] = ‘Australia’;

 

In Above code, the index(key) is assigned to zero. In case an integer indexes are already assigned, then PHP take largest index +1 as index(key).

 

To delete an element from associative array, unset is used. In unset function passed, the key to delete particular element.

 

unset($countrycode[‘fr’]);

 

To delete , the entire array code

unset($countrycode)

 

For variable substitution, you have to omit the quotes inside square bracket for a string key.

 

echo “<br> $statecode[MP] “;

 

or you can write

 

echo “<br> {$statecode[‘MH’]}”;

 

Foreach loop is also used in array to process all elements in an array which has gaps.

 

$countrycode = array();

$countrycode[“in”] = “India”;

$countrycode[‘ca’] = “Canada”;

$countrycode[‘fr’] = “France”;

$countrycode[‘usa’] = “America”;

unset($countrycode[‘fr’]);

foreach($countrycode as $cc => $con)

{

echo “<t> $cc => $con “;

}

 

Will display

 

in => India ca => Canada usa => America

you can view video on Array

References:

 

1. Luke Welling, Laura Thomson: PHP and MySQL Web Development, Pearson,

2.W. Jason Gilmore: Beginning PHP and MySQL 5 From Novice to Professional,Apress

3. Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec, Jeremy Stolz, Michael K.Glass: Beginning PHP5, Apache, and MySQL Web Development, Wrox,

4. Robin Nixon: Learning PHP, MySQL, and JavaScript, O’Reilly Media

5. Ed Lecky-Thompson, Heow Eide-Goodman, Steven D. Nowicki, Alec Cove:Professional PHP, Wrox

6. Tim Converse, Joyce Park, Clark Morgan: PHP5 and MySQL Bible

7. Joel Murach, Ray Harris: Murach’s PHP and MySQL, Shroff/Murach

8. Ivan Bayross, Web Enabled Commercial Application Development Using HTML/Javascript/DHTML/PHP , BPB Publications

9. Julie C. Meloni, Sams Teach Yourself PHP, MySQL and Apache All in One, Sams

10. Larry Ullman, PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide,Pearson Education

11. http://www.php.net

12. http://www.w3schools.com/

13. http://www.tutorialspoint.com/