+ 1
What is the meaning of this?
foreach ( $foo as $key => $bar) { $baz = $bar; }; Please help! Thanks :)
3 ответов
+ 2
A good explanation is here: http://php.net/manual/en/control-structures.foreach.php
In a simple way, foreach is looping through an array or object, $foo, and each time it's grabbing the current elements key and assigning it to $key, while also assigning the keys value to $bar.
For example,
$foo = array( 1, 2, 3 );
On the first iteration of the foreach loop, $key will equal 0, and $bar will equal 1.
Just like if you tried, $bar = $foo[0];, $bar will equal 1 and 0 is basically the $key.
You can also set the key yourself,
$foo = array( "one" => 1, "cat" => 2, "food" => 3 );
This time, on the first iteration, $key will equal "one", while $bar equals 1, second iteration, $key equals "cat" and $bar equals 2.
The $baz bit is simply assigning the value of $bar to $baz.
Hope that helps.
+ 1
It's not what you think!
this site shows looping through arrays with loops, keys and keys/values:
http://www.hackingwithphp.com/5/3/0/the-two-ways-of-iterating-through-arrays
+ 1
Thanks man, that really helps.