How to Iterating Through an Array in PHP ?
Last Updated :
17 Jan, 2024
Arrays are fundamental data structures in PHP, and the ability to iterate through them is crucial for manipulating and processing data. In this article, we will explore various approaches to iterate through arrays in PHP.
Using for
Loop
The PHP for
loop is a basic way to iterate through an array. It is useful when you need to access array elements by their index.
PHP
<?php
$arr = [1, 2, 3, 4, 5];
$length = count ( $arr );
for ( $i = 0; $i < $length ; $i ++) {
echo $arr [ $i ] . ' ' ;
}
?>
|
Using foreach Loop
The PHP foreach loop is an method to iterate through an array. There is no need of index number in foreach loop.
PHP
<?php
$arr = [1, 2, 3, 4, 5];
foreach ( $arr as $val ) {
echo $val . ' ' ;
}
?>
|
Using while Loop with each() Function
The PHP each() function can be used in combination with a while loop to iterate through an array while maintaining the internal pointer.
PHP
<?php
$arr = [ 'apple' , 'banana' , 'cherry' ];
while ( $element = each( $arr )) {
echo $element [ 'key' ] . ' => '
. $element [ 'value' ] . "\n" ;
}
?>
|
Output
0 => apple
1 => banana
2 => cherry
Share your thoughts in the comments
Please Login to comment...