note 85120 added to control-structures.foreach
| From: | brian at diamondsea dot com | Date: | Fri, 15 Aug 2008 15:15:04 +0000 |
| Subject: | note 85120 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-143526@lists.php.net to get a copy of this message | ||
A common problem is having PHP generate an error when trying to iterate through an array that may
sometimes have no data in it. This causes PHP to generate a warning such as:
Warning: Invalid argument supplied for foreach() in test.php on line 14
You can prevent this error by type-casting the foreach variable as an array type using
"(array)" before the array variable name.
<?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";
?>
Outputs:
Test 1:
Key a, Value 1
Key b1, Value 2
Key b2, Value 3
Key c, Value 4
Key d, Value 5
Test 2:
Warning: Invalid argument supplied for foreach() in /home/bgallagher/test.php on line 16
Test 3:
Done.
----
Server IP: 69.147.83.197
Probable Submitter: 63.217.142.210
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/85120
Del: integrated -- https://master.php.net/note/delete/85120/integrated
Del: useless -- https://master.php.net/note/delete/85120/useless
Del: bad code -- https://master.php.net/note/delete/85120/bad+code
Del: spam -- https://master.php.net/note/delete/85120/spam
Del: non-english -- https://master.php.net/note/delete/85120/non-english
Del: in docs -- https://master.php.net/note/delete/85120/in+docs
Del: other reasons-- https://master.php.net/note/delete/85120
Reject -- https://master.php.net/note/reject/85120
Search -- https://master.php.net/manage/user-notes.php