PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
$arr = array("one", "two", "three");
//set up array
reset ($arr);
//start at the beginning of the array
foreach ($arr as $value) {
echo "Value: $value<br />\n";
}
/*
--Output--
Value: one
Value: two
Value: three
*/
?>
PHP.net:
foreach (array_expression as $key => $value) statement
And the => assigns the value, right?
If you have :
$array = array(
'foo' => 'bar',
'foo2' => 'bar2'
);
then
foreach($array as $key=>$value){
echo $key.' '.$value.'<br />';
}
will show
foo bar
foo2 bar2
ie foo and foo2 are the keys, bar and bar2 are the values. In a simple array like $array = array('one', 'two', 'three') then the key is the element index (0, 1 and 2) and the values are 'one', 'two' and 'three'.
Ahh okay. So the $array part in the foreach function is the "object" to look in, the key and values is the stuff in the array (in this example) and the echo part is just displaying it. Got it. I guess the "as" part is throwing me off.
I don't know where it is on my comp, or whatnot, but there was an example that used this foreach, but had $_POST in the first spot for the foreach, something like:
Yeah, looks fine. Just be aware that when using foreach() on $_POST like that you usually want to 'ignore' the submit button (and possible other keys) and concentrate on the actual form fields/values.
You can 'ignore' the submit button by doing something like,
if($key != 'submit'){ .. process the other keys/values here .. } inside the foreach bit.
Yeah, looks fine. Just be aware that when using foreach() on $_POST like that you usually want to 'ignore' the submit button (and possible other keys) and concentrate on the actual form fields/values.
Well, lets say you want to 'do something' with the form values that were submitted, you usually don't want to do anything with the submit button (which will appear in the $_POST array). So if for example you were writing some test code that displayed all the form names and values posted then you might do something like :
<?php
//first check if the submit button was pressed
// *you'de normally use another element for this, but i'm checking the submit
// button for simplicities sake
if(!empty($_POST['submit'])){
foreach($_POST as $key=>$val){
if($key != 'submit'){ //ignore the submit button
echo $key.' '.$val.'<br />';
}
}
} else {
//this is were you might put the forms html
}
?>
This will ignore the submit button in the output as you usually don't care about processing it, you only care that it was pressed in the first place.