Sunday 29 May, 2011

Lesson 4 PHP array

Retweet this button on every post blogger
In PHP it is very simple to define array and traverse them easily.

Example : 
<html>
<head><title>PHP array</title></head>
<body>
<?php
$name = array("john", "bill", "steve"); // an simple array

for($i=0; $i<count($name); $i++ ) {
    echo "$name[$i]<br/>";
}
?>
</body>
</html>

OUTPUT :- 
john
bill
steve

though  this is a very basic type of array traversing PHP provide some advanced mean of array traversing using foreach loop
An example using foreach loop : -

<html>
<head><title>PHP array traverser using foreach loop</title></head>
<body>
<?php
$name = array("john", "bill", "steve"); // an simple array
   foreach ($name as $var) {
        echo "$var<br/>";
  }
?>

</body>
</html> 
Output :- 
john
bill
steve
working of foreach loop : -
1. first it implicitly determine the length of array
2 than it traverse array till the end.
3. at each iteration it creates a variable $var for each element of passed array.
Simple!! 
array traversing using foreach loop require less number of steps than conventional for loop.

Multi dimensional array traversing : -
multi dimension array are simply array within one array.
e.g.
$student  =  array(array("Math", "Physics", "Chemistry"), array("90","76","66"));
here is an student array with size two containing two secondary array for subject ans marks.
<html>
<head><title>PHP Multi dimensional array traversing</title></head>
<body>
<?php
$student  =  array(array("Math", "Physics", "Chemistry"), array("90","76","66"));
// an simplemulti dimesional array

$sub = 0; // index of subject array.
$marks = 1; // index of mark array.

for ($i=0; $i<count($student[$sub]); $i++)
{
    echo $student[$sub][$i]." : ".$student[$marks][$i];
    echo "<br/>";    
}
?>
</body>
</html> 


Output will be : 
Math  :  90
Physics : 76
Chemistry : 66

Adding elements to array dynamically :-
  <html>
<head><title>PHP adding  array elements dynamically</title></head>
<body>
<?php
$example = array("a","b","c");

$example[] = "d";
foreach ($example as $new) {
    echo "$new<br/>";
}
?>

</body>
</html>
Output : - 
a
b
c
d

No comments:

Post a Comment