Good Weekend Folks!

I have a question.
I do not understand how php knows how to define this variable $value in the following example since it has not been declared. How does it know what that variable represents since no reference or pointer has been assigned to it ? Strange!


<html> <body> <?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);

         foreach( $numbers as $value ) {
            echo "Value is $value <br />";

         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";

         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
      ?> </body> </html>

I thought "array_values()" was supposed to be there in the above example but "$value" is there instead.
What is the difference between the 2 ?

The following seems to be in pdo, which I haven't started learning just yet:

8 Months
Discussion Span
Last Post by diafol

$value is a dynamic variable that only lives within the scope of the loop it is used in. You have declared it with the loop declaraction.


As rubberman wrote you declared the $value inside the foreach for this array iteration.

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

There are more than that about arrays iteration in PHP (and differences in versions) but I don't want to mess you with these.

Just a quick comment , $value doesn't "live" only within the scope of the loop it is used in.

$arr = ["a","b","c"];
foreach($arr as $value)
echo $value;

Elsewhere, I understood from another programmer's hints that, the $numbers value would increment on each loop to $value.
The $numbers value would remain the same on each loop but not the $value's value.
I get it now.

This thread can be closed now so how do I close it ?


Edited by UI


Press the big solved button. Only you can do this. Threads can only be closed by moderators. This is almost never done unless a thread spirals out of control for some reason.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.