Home  >  Article  >  Backend Development  >  How to loop over an array in PHP

How to loop over an array in PHP

autoload
autoloadOriginal
2021-04-14 10:30:344714browse

How to loop over an array in PHP

This article mainly uses four methods to traverse the array: a. Use for loop b .Use while() loop c.Use foreach() loop d.Use do-while() loop.

1.Use for loop

<?php
    $a=array(2,20,34,45,234,324234,324,324);
    for($i=0;$i<sizeof($a);$i++){
        echo $a[$i]."<br>";
    }
?>

2.Use while() loop

<?php
    $a=array(2,20,34,45,234,324234,324,324); 
    $i=0;
    while($i<sizeof($a)){
         echo $a[$i]."<br>";
         $i++;
    }
?>

3. Use foreach() loop

 <?php
    $a=array(2,20,34,45,234,324234,324,324);
     foreach($a as $value){
         echo $value."<br>";
    }
    
  ?>

4. Use do-while() loop

<?php
    $a=array(2,20,34,45,234,324234,324,324);    
    $c=0;
    do{
        echo $a[$c]."<br>";
        $c++;
    }while($c<sizeof($a));
 ?>

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of How to loop over an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn