Using PHP foreach

The PHP manual describe clearly how to use the foreach without throwing an error – “The foreach construct provides an easy way to iterate over arrays. And foreach works only on arrays and objects,…”

Sometimes this is hard to understand. The best way to learn and study is by seeing an example.

The following PHP example shows how to read an external text database, and finally getting the individual data of each record.

The contents of the external text database is:

alex,male,58
kathy,female,52
peter,male,64

This is a very simple text database – only 3 records, each record has only 3 data, and each data is separate by a comma.

Here’s the completed PHP codes:

<?php 

$lines = file('test-list.txt'); 

// $lines is now a 2-dimensional array
// each line is a record
// we can use count() to get the array length
echo "Total number of lines are: " . count($lines);
echo "<br><br>";

// Use foreach to iterate over the $lines array
// On each iteration, the value of the current element is assigned to $value
// foreach ($lines as $value) { also works without assign the current element's key to the $key variable
foreach ($lines as $key => $value) {

    // show the record of each line
    echo "This is line " . $key;
    echo "<br>";

    // explode the record
    $contents = explode(",", $value);

    //echo "The first item is " . $contents[0];
    for($i=0; $i<count($contents); $i++) {
        echo $contents[$i];
        echo "<br>";
    } // end for loop
} // end foreach

?>

The PHP codes are very simple and should very easy to understand. The first step is to read and get the external file (text database) into an array. The next step is to use foreach to iterate or run over the arrays. While running over the array and get the record one by one, the record is exploded and extract the data one by one.

The output of the above PHP codes are:

Total number of lines are: 3

This is line 0
alex
male
58
This is line 1
kathy
female
52
This is line 2
peter
male
64

Actually the PHP foreach can also be written like that:

foreach ($lines as $value) {
   ..... codes here
}

if you don’t need to use the $key value.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>