Jump to content

Question On The Variable (Array Value)


phpsane

Recommended Posts

Php Gurus,

 

I have been doing guess work all this time. But not any more. Just gonna ask.

Look at the following code:

 

Concentrate on line 5.

It is obvious the "$colors" represent the variable name of the whole array thing (or "column" or "row" in MS Excell terminology).

But what does the "$value" represent ? Each array's values (or "cell" value in MS Excell terminology) ?

So, the value of the variable $value changes on each loop. Right ? From "Red" to "Orange" at the end. Correct ?

Example:

 

1st loop:

$value = Red;

 

2nd loop:

$value = Green;

 

And so on.

 

Correct ?

<?php
$colors = array("Red", "Green", "Blue", "Yellow", "Orange");
 
// Loop through colors array
foreach($colors as $value){
echo $value . "<br>";
}
?>
Link to comment
Share on other sites

$value is an element in the array.

 

As for what happens, run the code and see for yourself.

 

Running the code showed me this:

 

Red

Green

Blue

Yellow

Orange

 

I figure, those values of the $value are related to the loop. 

Once I echo the value of the $value outside the loop then "Orange" (last value of the variable $value in the loop) is shown as the value.

What do I determine from all this ?

Well, I reckon the value of $value changed on each cycle and the echo inside the loop echoed each different value of the $value.

The final echo that was outside the loop, only echoed the final value of the $value.

 

<?php
$colors = array("Red", "Green", "Blue", "Yellow", "Orange");
 
// Loop through colors array
foreach($colors as $value){
echo $value . "<br>";
}
 
echo $value . "<br>";
 
?>

 

Result:

 

Red

Green

Blue

Yellow

Orange

Orange

 

That automatically means that the $value holds the values of each and every array. Right ?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.