Skip to content

Instantly share code, notes, and snippets.

@robbestad
Created June 30, 2013 20:21
Show Gist options
  • Select an option

  • Save robbestad/5896726 to your computer and use it in GitHub Desktop.

Select an option

Save robbestad/5896726 to your computer and use it in GitHub Desktop.
Getting rid of foreach error
<?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