10 January 2011

Php For Beginners (Lesson 6)

In this lesson we will be discussing array variables, array variables are just like ordinary variables except that an array variable can store multiple values in one single variable.

For example if you want to store names of 5 students then you need to have 5 variables. What if students total exceeds 500? Then you will need 500+ variables to store those names. In such situations we will use a single array variable to store the names of all the students.

Array variables have indexes associated with each value, so that the values can be easily accessed using their respective indexes. These indexes can be numeric as well as strings.

Numeric Index Array

Example
<?php 
$student_name[0]=”Bill”; 
$student_name[1]=”Max”; 
$student_name[2]=”John”; 
$student_name[3]=”Smith”; 
echo $student_name[0].” And ”.$student_name[3].” Are good students”; 
?>
The output of above example will be “Bill and Smith Are good students”.

String Index Array

Example
<?php 
$marks[‘bill’]=”96”; 
$marks[‘max’]=”32”; 
$marks[‘john’]=”54”; 
$marks[‘smith’]=”78”; 
echo “Bill secured ”.$marks[‘bill’].” marks”; 
?>
The output of above example will be “Bill secured 96 marks”.

Multidimensional Array

In multidimensional array each element of the main array can also be an array and each element in that array may be an array too, and so on.

Example
<?php 
$students=Array
(
[‘Bill’] => Array
(
[0] => 78
[1] => 86
[2] => 92
)
[‘Max’] => Array
(
[0] => 45
)
[‘John’] => Array
(
[0] => 76
[1] => 63
[2] => 78
)
); 
echo “Bill secured ”.$students[‘Bill’][2].” marks”; 
?>
The output of the above example will be “Bill secured 92 marks”.

References

http://www.php.net
http://www.w3schools.com

I guess we have discussed all the fundamental concepts of array variables, in case of any queries please feel free to comment on this post.


next Previous Lesson --- Next Lesson next

No comments: