Concept
How can you iterate over indexed and associative arrays in PHP?
ComputerScienceOne / Iteration
"If we have an array in PHP that we know is 0-indexed and all elements are contiguous, we can use a normal for loop to iterate over its elements by incrementing an index variable.\n\nfor($i=0; $i<count($arr); $i++) {\n\nprint $arr[$i] . \"\n\n\";\n\n}\n\nThis fails, however, when we have an associative array that has a mix of integer and string keys or “holes” in the indexing of integer keys. For this reason, it is more reliable to use foreach loops. There are several ways that we can use a foreach loop. The most general usage is to use the double arrow notation to iterate over each key-value pair."
Related Ideas
- How can you iterate through an array using foreach?ComputerScienceOne · Adding Elements
- How does PHP use foreach loops to iterate over array elements?ComputerScienceOne · Foreach Loops
- How are foreach loops used to iterate over array elements in PHP?ComputerScienceOne · Do-While Loops
- How does the foreach syntax iterate over an array in PHP?ComputerScienceOne · Normalizing a Number
- Can PHP array indices be non-contiguous?ComputerScienceOne · Strings as Indices
- How can key-value pairs be initialized in a PHP array?ComputerScienceOne · Non-Contiguous Indices
- How do you create and index arrays in PHP?ComputerScienceOne · Creating Arrays
- How can strings be used as indices in PHP arrays?ComputerScienceOne · Non-Contiguous Indices