Petlja foreach olaksava rad sa slozenim promenljivama, kao sto su nizovi, jer nizovi sadrze vise stavki sa podacima. Ova petlja omogucava da prolazite kroz niz, a da pri tome ne koristitite indeks petlje.
foreach (izraz_niza as $vrednost) iskaz
foreach (izraz_niza as $kljuc => $vrednost) iskaz
Primer: prolazak kroz niz boja, pri cemu se svaki pit stampa odredjeni tekst.
<?php
$niz = array("zelena", "narandzasta", "crvena");
foreach ($niz as $vrednost) {
echo "Trenutna boja: $vrednost<br>";
}
?>
Rezultat:
Trenutna boja: zelena
Trenutna boja: narandzasta
Trenutna boja: crvena
Loop foreach facilitates working with complex variables, such as arrays, because arrays contain several items with data. This loop allows to pass through array, and doing so you don't use the loop index.
foreach (array_expression as $value) statement
foreach (array_expression as $key => $value) statement
For example, passing through array of colors, where every time you print a specific text.
<?php
$colorArray = array("green", "orange", "red");
foreach ($colorArray as $value) {
echo "Current color: $value<br>";
}
?>
Result:
Current color: green
Current color: orange
Current color: red
foreach (izraz_niza as $vrednost) iskaz
foreach (izraz_niza as $kljuc => $vrednost) iskaz
Primer: prolazak kroz niz boja, pri cemu se svaki pit stampa odredjeni tekst.
<?php
$niz = array("zelena", "narandzasta", "crvena");
foreach ($niz as $vrednost) {
echo "Trenutna boja: $vrednost<br>";
}
?>
Rezultat:
Trenutna boja: zelena
Trenutna boja: narandzasta
Trenutna boja: crvena
Loop foreach facilitates working with complex variables, such as arrays, because arrays contain several items with data. This loop allows to pass through array, and doing so you don't use the loop index.
foreach (array_expression as $value) statement
foreach (array_expression as $key => $value) statement
For example, passing through array of colors, where every time you print a specific text.
<?php
$colorArray = array("green", "orange", "red");
foreach ($colorArray as $value) {
echo "Current color: $value<br>";
}
?>
Result:
Current color: green
Current color: orange
Current color: red
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.