Previous | Home | Next |
If you using an associative array that you want to iterate through. then the PHP provides an easy way to use every element of an array with the Foreach statement.
A For Loop and While Loop will continue until some condition fails, but the For Each loop will continuing until it has gone through every item in the array.
Example:
We have using an associative array that stores the names of all employee in any company as the keys, and the keys values is any employee being their age. We want to know how old everyone is at work so we use a Foreach loop to print out everyone's name and age.
PHP Code: <?php $emp Ages; $emp Ages["Amit"] = "28"; $emp Ages["Anurag"] = "16"; $emp Ages["Abhas"] = "35"; $emp Ages["Akash"] = "46"; $emp Ages["Aditya"] = "34"; foreach( $emp Ages as $key => $value){ echo "Name: $key, Age: $value <br />"; } ?>
Output:
Name: Amit, Age: 28 Name: Anurag, Age: 16 Name: Abhas, Age: 35 Name: Akash, Age: 46 Name: Aditya, Age: 34
Syntax:
$something as $key => $value
The operator "=>" represents the relationship between a key and value. You can imagine that the key points => to the value. In our example we named the key $key and the value $value. However, it might be easier to think of it as $name and $age. Below our example does this and notice how the output is identical because we only changed the variable names that refer to the keys and values.
PHP Code: <?php $emp Ages; $emp Ages["Amit"] = "28"; $emp Ages["Anurag"] = "16"; $emp Ages["Abhas"] = "35"; $emp Ages["Akash"] = "46"; $emp Ages["Aditya"] = "34"; foreach( $emp Ages as $name => $age) { echo "Name: $name, Age: $age <br />"; } ?>
Output:
Name: Amit, Age: 28 Name: Anurag, Age: 16 Name: Abhas, Age: 35 Name: Akash, Age: 46 Name: Aditya, Age: 34
Previous | Home | Next |