Home    Articles

 

How to use foreach in php

 

Using foreach is very useful when we want to use data from arrays.

Foreach can be used also for objects, but foreach works only with arrays and objects. You will get errors if you will try to use another data types.

For an array like this one, you can use foreach in two ways.

array
(
 [0]=>apple
 [1]=>peach
 [2]=>orange
)

First way will have the result: ” apple,peach,orange, ”

<?php
$data = array("apple","peach","orange");
foreach ($data as $value) 
{
    echo $value.',';
}
?>

The second way will have the same result: ” apple,peach,orange, ” but we will use a different syntax.

<?php
$data =  array("apple","peach","orange");
foreach ($data as $key=>$value) 
{
    echo $value.',';
}
?>

What is the benefits of using the second syntax?
We can use $key,so we can see if the key is a string or a number.We may need this at some time.
The $key is very useful, you may need it to delete or replace its value.

Those are the basics. You can use the code bellow to debug your array.

 echo '<pre/>';print_r($your_array);
 exit; //this will end your code, the code will stop here.

 

by