Project 7: For Each Array

For Each Array

The foreach loop in PHP is a powerful tool for iterating through arrays. Here’s a quick explanation about For Each Array:

  • What it does: It allows you to process each element in an array one by one.
  • Syntax: foreach ($array as $key => $value) { … }
    • $array: The array you want to loop through.
    • $key: (Optional) Represents the index (position) of the current element.
    • $value: Represents the actual value of the current element.
    • …: This is where you write the code that will be executed for each element.

Example:

PHP Code

$fruits = [“apple”, “banana”, “orange”];

foreach ($fruits as $fruit) {

echo “I love $fruit!  “;

}

This code will print: “I love apple! I love banana! I love orange!”

Here’s another example of For Each Array.

Output

Benefits:

  • Easy to use and understand.
  • Works with both numeric and associative arrays.
  • Makes iterating through arrays efficient.

 

Search

PHP Projects

School Projects

Collage Projects

Join Us

Follow Us

Recent Blogs