ITP

IMCA - Web Development Using PHP

What is foreach loop ? Explain

In : IMCA Subject : Web Development Using PHP

In PHP , the foreach loop is a control structure specifically designed to iterate over arrays . It provides an easy and clean way to loop through each element of an array  without needing to manage a counter or index manually.

There are two main syntaxes: 

1. Using value only:

foreach ($array as $value) {
// Code to execute for each element
}
  
  • $array: The array you want to loop through.
  • $value: Holds the value of the current element in the iteration.
 

2. Using both key and value: 

foreach ($array as $key => $value) {
// Code to execute for each element
}
 
  • $key: Holds the current key (index) of the element.
  • $value: Holds the current value of the element.

Example :

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {
    echo "Fruit: $fruit";
}

About us

A truly open platform where you may ask questions and get answers. We also provide comprehensive and easy-to-understand answers to question papers.  discover...

Site status

Flag Counter

Privacy Policy

Sitemap