-1

I'm running a small loop to get the number of items in an array stored in local storage. Then passed to a Session Variable. I tried using Count() but that threw an error. So I then tried this code but I get the following error:- Any clues?

Warning: Invalid argument supplied for foreach() in --etc. directory code line

$ItemCount = 0;
        $Data = json_decode($_SESSION['ItemArray']);
        foreach($Data as $item){
            $ItemCount = $ItemCount+1;
        }
James
  • 7
  • 3

1 Answers1

0

$Data is not an array or an iterable object. Add a second parameter to json_decode to get an array returned.

$ItemCount = 0;
$Data = json_decode($_SESSION['ItemArray'], true);
foreach($Data as $item){
    $ItemCount = $ItemCount+1;
}
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
  • Provided some assumptions on the data structure which OP didnt really provide – GetSet Apr 23 '20 at 10:35
  • @GetSet Error message is clear about that. An empty array would not cause any error. – Markus Zeller Apr 23 '20 at 10:53
  • Makes sense, however we dont know what is coming out of "session" based on non-existent OP code on that demonstration, nor are we clued in on a data structure by same source. I might add, OP seems to have abandoned commenting her/himself further indicating a "we will never know" scenario. – GetSet Apr 23 '20 at 11:51
  • I don't know what to discuss. The error said, it is no array. Independent what he is putting in, it does not change the issue. – Markus Zeller Apr 23 '20 at 12:03
  • I get you. However perhaps your remark should be comments level since we dont know OP other logical errors being blind to a data structure – GetSet Apr 23 '20 at 12:07
  • Providing code in comments is awful (in current SO comment formatting). That's why made it as an answer, too. As you can see I already commented it. – Markus Zeller Apr 23 '20 at 12:24