note 85120 deleted from control-structures.foreach by googleguy

From: Date: Wed, 14 Nov 2012 22:30:26 +0000
Subject: note 85120 deleted from control-structures.foreach by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191970@lists.php.net to get a copy of this message
Note Submitter: brian at diamondsea dot com ---- 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.

« previous php.notes (#191970) next »