Manipulating array values in PHP

Asked

Viewed 103 times

-1

I’m storing an array in a Session, but I’m not able to manipulate it. How do I add all the values of the array?

I tried this way:

$item = $_SESSION['item'];
$total = 0;
foreach($item as $x) {
    $total += $x;
}
echo $total;
exit();

however, the return is:

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\quiz_Acaro\final.php on line 70
0
  • Can do var_dump($item) in the second line and post the result?

  • @Andersoncarloswoss 23string(2) "23"

  • So there’s a string in your session, not a array. How you set the session?

  • @Andersoncarloswoss is a step by step. in the first part, the user has checkboxes to mark, and sends the values via post. sending via post, var_dump($item) returns the array, not string. so, probably the error is from step 2 to step 3 (there are 3 steps)

  • @Andersoncarloswoss array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }

  • Then ask the question your complete code, especially the code referring to steps 2 and 3, whatever that means.

  • I got it. Thanks for helping :D

  • How did you get it? Were you setting the session wrong? What was the error?

  • @Andersoncarloswoss in step 2 I was turning the array into string at the time of sending to step 3

  • 1

    Then put the full code in the question and then answer how you solved the problem. In my view, the error was in the definition of the session, not in the reading, so the answers given, even correct, would not solve the problem described.

Show 5 more comments

2 answers

3


This error means that you are trying to iterate on an element that is not an array.

First Voce needs to know/ensure that item valir is an array

$item = $_SESSION['item'];
$total = 0;

if(is_array($item)){
    foreach($item as $x) {
        $total += $x;
    }
    echo $total;
}else{
    echo 'Ops! Esse item nao é um array';
}
exit();

2

The mistake Invalid argument supplied for foreach() It happens when you pass the foreach a non-transferable value.

Therefore, you should have a check if really the value $_SESSION['item'] can be iterated:

if (isset($_SESSION['item']) && is_array($_SESSION['item']) {

     // Resto do seu código aqui
}

I chose to use isset, because if you use is_array directly, will be issued a E_NOTICE, if the index 'item' of array does not exist.

  • And why not is_iterable? :D

  • @Andersoncarloswoss didn’t know this existed in PHP :D. I only use PHP 5.6

Browser other questions tagged

You are not signed in. Login or sign up in order to post.