2

http://php.net/manual/en/control-structures.foreach.php

Trying to better understand the foreach loop. In the documentation above it states "The first form loops over the array given by array_expression."

What in the world is an array_expression?

samayo
  • 16,163
  • 12
  • 91
  • 106
Kohler Fryer
  • 764
  • 2
  • 8
  • 17

2 Answers2

2

An array_expression is any expression that results in an array. So these are expressions that are not arrays themselves but result in an array when evaluated:

foreach(range(1, 5) as $val){}

Or:

foreach($array = range(1, 5) as $val){}

Or:

class Test {
    public static function do_it() {
        return range(1, 5);
    }
}

foreach(Test::do_it() as $val){}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

From the php manual's descriptionpage

Expressions are the most important building blocks of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

So, this means array_expression is just a dumb dummy text to let you know that the foreach takes array function.

In this case,

$arr = array(1, 2, 3);

foreach ($arr as $value) {
   var_dump($value);
}

would result:

int(1) int(2) int(3)
samayo
  • 16,163
  • 12
  • 91
  • 106
  • I would also show example with `foreach (array(1,2,3) as &$value) {` (or similar style) to show the differences to use an array in the loop – Alon Eitan Aug 04 '17 at 16:58
  • But how can an array ever be an expression? – Kohler Fryer Aug 04 '17 at 17:02
  • I struggled over the same thing when I started to learn PHP. Here is a page dedicated entirely to what an expression means [Expressions are the most important building block....](http://php.net/manual/en/language.expressions.php) – samayo Aug 04 '17 at 17:06