Let's say you have an array of many things like this:
$array = array("dog","cat","giraffe","bear");
You can use a foreach to very easily pull all of these out and display them. Here is how I do it, feel free to leave a comment with a different way because we all know there are thousands of ways to do things in programming.
Because we have saved our array in a variable called $array this is how we would do the foreach loop.
foreach($array as $animal){
echo $animal."\n";
}
Normally, I would use a br tag to break a line, but blogger picks it up and actually does a line break instead of just showing the text. So pretend like the \n is a br tag.
Explanation:
Now let me explain what this is doing:
First, for every element in the array we assign it to animal so the first time it runs $animal is "dog" so it echoes our "dog" then gives a line break. It repeats this until it echoes all the elements in the array.
You can also use a foreach loop to run through xml documents, objects, and all kinds of other neat things you need to go through to pull out data from any source.
If you have any questions or just want to know more about foreach loops please shoot me an email or leave a comment!
No comments:
Post a Comment