Maybe PHP 7 will fix this madness, but at time of writing the stock PHP versions in Debian Jessie and Ubuntu Wily behave as outlined above.Īnyway, the short version is that you can avoid this by adding unset( $value ) immediately after the first foreach. My intuition strongly suggests to me that $value should go out of scope after the first foreach loop, but apparently my intuition is wrong. It is recommended to destroy it by unset().” As the PHP documentation states, “Reference of a $value and the last array element remain even after the foreach loop. The reason is that the first foreach loop passes values by reference ( &$value) while the second passes them by value ( $value). Okay, so it’s not really inexplicable, just very unexpected. Yes, that’s right, the final key inexplicably appears to have the same value as the previous key, despite print_r suggesting otherwise. Make sure your rewind() implementation tries to grab the first result so that the subsequent call to valid() will know whether or not the result set is empty. If you also expected that, you would be wrong. Otherwise your code will break if the same iterator is used in two consecutive foreach loops when the first loop terminates with a break statement before all the results are iterated over. Now, call me crazy, but I expect both the print_r call and the second foreach loop to return pretty much the same information: the keys, a to f, and their corresponding values, 1 to 6. We use foreach loop mainly for looping through the values of an array. A local function scope contains the function's parameters and the variables that are set inside the function body. PHP then iterates over this new copy of the array rather than the original one. In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. This is better than a foreach loop because it only loops over the elements you want. Do variables in the for / foreach loop have a local scope If so, how do I make it global There are only two kinds of scopes in PHP: the global scope and local function scope. PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreach loop. 0, 'b' => 0, 'c' => 0, 'd' => 0, 'e' => 0, 'f' => 0 ) The continue causes the foreach to skip back to the beginning and move on to the next element in the array. Consider this slightly contrived example code: I just spent a couple of hours debugging something really counterintuitive, where PHP’s print_r seemingly told me that an array had different content to the content that the same array contained according to a foreach loop.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |