Bifalgorithm post · Computer science one · Iteration
How can you iterate over indexed and associative arrays in PHP?
How can you iterate over indexed and associative arrays in PHP? (Computer science one · Iteration) — "If we have an array in PHP that we know is 0-indexed and…
Ideas in this flowchart
- Iterating over PHP arrays according to their key structure
- A normal for loop applies when the array is zero-indexed and all elements are contiguous
- The for loop iterates by incrementing an index variable
- The loop starts at zero, continues while the index is below count($arr), and increments the index
- Example: for($i=0; $i<count($arr); $i++) { print $arr[$i]; }
- The for loop fails with associative arrays containing mixed key types or holes in integer indexing
- Foreach loops are more reliable for arrays with irregular keys
- A foreach loop can be used in several ways
- The most general form uses double-arrow notation to iterate over each key-value pair