Multidimensional arrays are useful for all sorts of things, such as holding multiple database records and storing data to display in tables. In this tutorial you’ve seen how to create, manipulate, and loop through multidimensional arrays in PHP. ![]() Here’s an example that creates a 2-dimensional array of movie information, then loops through the array, displaying the information in the page: ![]() For each of those top-level elements, the inner loop moves through the array contained in the top-level element, and so on.The outer loop reads each element in the top-level array.To do this, you need to create nested foreach loops - that is, one loop inside another: Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. (Find out more about print_r() in Working With Array Elements in PHP.) Looping through multidimensional arrays The last example uses $movies to access the entire nested array contained in the first element of the top-level array, then uses print_r() to display the array’s contents. The nested array contained in the first element:Īrray ( => Rear Window => Alfred Hitchcock => 1954 ) The above code produces the following output: Here are some examples that access various elements in the $movies multidimensional array created earlier:Įcho "The nested array contained in the first element:" If you want to access the second-level array elements in a 2-dimensional array, just use 2 sets of square brackets - for example: To access multidimensional array elements, you can use the same square bracket syntax that you use with regular arrays. Here’s a 3-dimensional array:Īccessing elements in a multidimensional array You can nest arrays as many levels deep as you like (although it’s rare to go higher than 3 levels). The following example creates an indexed array containing 3 associative arrays: You can also use associative arrays in multidimensional arrays. Each element is itself an array containing 3 values. The above example creates a 2-dimensional array. The difference is that each element in the array you create is itself an array. ![]() You create a multidimensional array using the array() construct, much like creating a regular array. In this tutorial you learn how to create multidimensional arrays, how to access elements in a multidimensional array, and how to loop through multidimensional arrays. ![]() They can also hold other arrays, which means you can create multidimensional, or nested, arrays. Array elements in PHP can hold values of any type, such as numbers, strings and objects.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |