Created
June 30, 2013 20:21
-
-
Save robbestad/5896726 to your computer and use it in GitHub Desktop.
Getting rid of foreach error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // double any value whose key starts with 'b' | |
| $arr = array('a'=>1, 'b1'=>2, 'b2'=>3, 'c'=>4, 'd'=>5); | |
| $non_array = null; | |
| // Normal usage with an array | |
| print "Test 1:\n"; | |
| foreach ($arr as $key => $val) { | |
| print "Key $key, Value $val\n"; | |
| } | |
| // Normal usage with a non-array (undefined or otherwise empty data set) | |
| // Outputs: Warning: Invalid argument supplied for foreach() in test.php on line 16 | |
| print "Test 2:\n"; | |
| foreach ($non_array as $key => $val) { | |
| print "Key $key, Value $val\n"; | |
| } | |
| // By casting the $non_array to an (array) type, it will function without error, skipping the loop | |
| print "Test 3:\n"; | |
| foreach ((array) $non_array as $key => $val) { | |
| print "Key $key, Value $val\n"; | |
| } | |
| print "Done.\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment