Here print out all the children names along with their ages.Īgain, just like with the first loop, we don't have the use the variables $key and $value we can really names these variables anything.įor example, we can change them to $name and $age, so that you can know what each one represents.Īnd it will work the same as the before code. So when printing out the array, we want to know and print out both the keys and values of each element of the array.Īnd we can do this, using the foreach loop in the following format: Here, the keys represent the names of the children and the values represent their ages. Here in this array, the keys are John, Peter, and Bill. Let's say we have the following array below: The other way a foreach loop can be used is to specify both the keys and values of an array. In other words, PHP will know that the variable after the as keyword is the variable which stores the values of the array, and it can be named anything. We can change value to $value to $kids, so that our new code is: Realize that although the variable $value is used with the as keyword, it can be named anything. You can see that the foreach loop prints out all of the elements of the array. Using the foreach loop in the following format below, we can print out all the values of the above array: Though PHP creates the keys 0, 1, 2, 3, 4 as an index, many times we aren't interested in these values. Say, that we have an array that only has values specified, and not keys.įor example, let's take the following array below:įor an array like this, many times we are only interested in the values of the elements of the array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |