Last Updated: February 25, 2016
· simon_hen

Php's foreach with string key

Normally, when you are using associated array, you're, maybe, giving string to the key as here:

$my_array = array(
"js_folder"       =>"Js Folder",
"css_folder"      =>"CSS Folder",
"fonts_folder"    =>"Fonts Folder",
"template_folder" =>"Templates Folder",
"upload_folder"   =>"Uploads Folder"

The problem is that php is going to return an error like this :

Warning: Invalid argument supplied for foreach() in /random/file/path.php on

line #line-number

Just write (array) in the beginning of your foreach and everything is going to be fine:

foreach((array) $my_array as $key => $value)
       echo $key;
       echo $value;
Say Thanks

1 Response
Add your response


It won't. It will give such error if $my_array is not an array and this has nothing to do with string keys.

over 1 year ago ·