Home >Backend Development >PHP Tutorial >What is the usage of foreach?

What is the usage of foreach?

藏色散人
藏色散人Original
2019-02-25 14:03:275478browse

Like any other language, loops in PHP are used to execute a statement or block of statements multiple times until and unless a specific condition is met. This helps users save time and effort writing the same code multiple times.

What is the usage of foreach?

Recommended manualphp complete self-study manual

foreach loop:This loop is used to traverse the array. For each counter in the loop, an array element is allocated and the next counter is moved to the next element. (Recommended: PHP Tutorial)

Syntax:

foreach (array_element as value) {
   //待执行的代码
}

Usage example:

<?php 
  
    $arr = array (10, 20, 30, 40, 50, 60); 
    foreach ($arr as $val) {  
        echo "$val \n"; 
    } 
      
    $arr = array ("Ram", "Laxman", "Sita"); 
    foreach ($arr as $val) {  
        echo "$val \n"; 
    } 
  
?>

Output:

10 
20 
30 
40 
50 
60 
Ram 
Laxman 
Sita
Recommended related articles:
1.Usage of foreach in PHP
2.Two uses of foreach in PHP as $key => $value
Related video recommendations :
1.Dugu Jiujian (4)_PHP video tutorial

This article is an introduction to the usage of PHP foreach, Hope it helps those in need!

The above is the detailed content of What is the usage of foreach?. 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