PHP: foreach
The PHP control statement, foreach{}, is a handy way to cycle through the elements of an array and perform the same operations on each. Foreach{} only works with arrays (both numerical and associative).
PHP Foreach Syntax
Array_expression: This is the array whose elements we want to process.
Value: This is the variable we want to assign the element to during each loop.
Statement: These are the instructions we want to perform during each iteration of the loop.
In the case of an associative array, the syntax can also look like this:
In this case, $key is assigned the associative element's key from the array.
How to Use Foreach Loops in PHP
Pretend we have the following array:
If we wanted to echo each of these names in turn, we could use a foreach{} loop:
This will cycle through the array, and echo the data contained in $value (which will be each name).
Comment:
$Array = (explode(" ",$copete));
foreach($Array as $key) {
$keywords = strtolower($key);
print "$keywords,";
}
I need to exclude for example: "to, from, etc".
Thanks.
$Array = (explode(" ",$copete));
foreach($Array as $key) {
$exclude = array("to","from");
$keywords = strtolower($key);
if(!in_array($keywords,$exclude)){
echo $keywords . ",";
}
}
I havn't checked it, but unless I made some stupid error, that will work.
explain anything except to people who already know what it does! "$key is assigned
the associative elemet's key" is utterly lacking in meaning unless you bother to explain
what "associative" and "key" mean.
Nice work!
foreach ($namearray, $addressarray, $telarray as $value)
something like that?
foreach ($movies as $movie_id => $title)
I would like that each line has a different colour depending of a value in the database (if this row is A=Red, if the row has the value B=Blue).
How can I do that?
Thanks :-)
I have this foreach loop
foreach ($_SESSION['qty'] as $k => $p) {
if (isset($_SESSION['qty'][$p])) {
echo "I would like $p x {$_SESSION['product'][$k]} please.";
}
}
For some reason {$_SESSION['product'][$k]} will not write when in the loop but is getting picked up outside the loop.
Any body see what's going wrong here?
any help would be great
I think he is just trying to experiment how the site will do he ahs some plans to monetize this site to make millions ;p
(nice link farm btw)