+ 1

What is the meaning of this?

foreach ( $foo as $key => $bar) { $baz = $bar; }; Please help! Thanks :)

26th Dec 2016, 11:37 AM
Berlianto
Berlianto - avatar
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.
26th Dec 2016, 12:32 PM
xmillsa
+ 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
26th Dec 2016, 12:35 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Thanks man, that really helps.
26th Dec 2016, 12:37 PM
Berlianto
Berlianto - avatar