i am new to php and want to understand the foreach loop. sorry if it is an offtopic and was earlier discussed, but i found little help from other posts.
below are 2 different arrays and the loops used for them to fetch out the keys-values (the first called $size is pretty easy and I have no problems with it; the second called $size2 loops thru an array, but i see error messages in the browser – please suggest what i did wrong):
one level array:
$size = array(
"day" => "friday",
"place" => "office",
"task" => "smalot",
);
foreach loop to fetch our key-values from $size (it works fine):
foreach ($size as $key => $value) {
echo $key . "=>" . $value . "";
}
two level array:
$size2 = array(
"day" => "friday",
"place" => "office",
"task" => "smalot",
"level2" => array(
"place" => "desk",
"laptop" => "lenovo",
"coffee" => "black",
)
);
foreach loop to fetch our key-values from $size2 (it works not properly):
foreach ($size2 as $key => $value) {
echo $key . "=>" . $value . "<br>";
foreach ($value as $subkey => $subvalue) {
echo $subkey . "=>" . $subvalue . "<br>";
}
}
the result of the foreach loop for $size2 is below:
day=>friday
Warning: foreach() argument must be of type array|object, string given in C:xampphtdocspdfparsersize.php on line 35
place=>office
Warning: foreach() argument must be of type array|object, string given in C:xampphtdocspdfparsersize.php on line 35
task=>smalot
Warning: foreach() argument must be of type array|object, string given in C:xampphtdocspdfparsersize.php on line 35
Warning: Array to string conversion in C:xampphtdocspdfparsersize.php on line 33
level2=>Array
place=>desk
laptop=>lenovo
coffee=>black
if i uncomment the inner loop, then i can fetch the key-values from upper array:
foreach ($size2 as $key => $value) {
echo $key . "=>" . $value . "<br>";
// foreach ($value as $subkey => $subvalue) {
// echo $subkey . "=>" . $subvalue . "<br>";
// }
}
result:
day=>friday
place=>office
task=>smalot
Warning: Array to string conversion in C:xampphtdocspdfparsersize.php on line 33
level2=>Array
but the goal is to fetch upper and inner key-values from an array and see no error messages. what shall i do? thanks again!
–