CopyPastehas never been so tasty!

Iterating array using for and while loop in PHP

by anonymous

  • 0
  • 0
  • 0
78 views

http://codingvilla.com/iterate-array-while-loop-php-single-article-654.aspx

Arrays:

 

Arrays are just like the variable that store values but arrays can use to store more than one value. Variable only store one value. There are three types of arrays

 

  • Numeric arrays
  • Associative array
  • Multidimensional array

 

For loop:

 

For each loop is used when we want to use every element of an array and we want to iterate through every element php provide us for each loop for this purpose.

 

While loop:

 

While loop has a control statement. While loop run the code when specified condition is true. The code repeats its iteration until the condition become false.

 

Syntax:

 

while (variable<end value)
        {
            code to be executed
        }

 

 

Iterate an array using for/while loop in php:

 

To iterate an array using for each and while loop is so simple. In the give code we use both control statement to iterate an array first we have for each loop to access each element of an array then we have an array loop.

 

Code:

 

<?php

$pc_parts = array();

     $pc_parts["Memory"] = "256 MB";

     $pc_parts["CPU"] = "Athlon Thunderbird";

     $pc_parts["Video Card"] = "Matrox";

     $pc_parts["Hard Drive"] = "IBM";

     foreach($pc_parts as $part_type => $part_name)

 {

          $buf = sprintf("Part name is: <strong>%s</strong> Part value is:

<strong>%s</strong>", $part_type, $part_name);

          echo $buf . "<br />";

     }

     echo "<br /><br />";

     reset($pc_parts);

     while (list($part_type, $part_name) = each($pc_parts))

     {

          $buf = sprintf("Part name is: <strong>%s</strong> Part value is:

<strong>%s</strong>", $part_type, $part_name);

          echo $buf . "<br />";

     }

?>

 

Above is a simple code to iterate for each and while loop in php.

 

This simple article tells that how we can iterate for each and while loop in php.

Add A Comment: