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;
}
Written by Henrotte Simon
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#