Manipulating array values in PHP [closed]

-1

I am storing an array in a session, but I am not able to manipulate it. How do I add all the array values?

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
    
asked by anonymous 03.11.2017 / 14:25

2 answers

3

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

First you need to know / ensure that the value of the item 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();
    
03.11.2017 / 14:38
2

The error Invalid argument supplied for foreach() happens when you pass foreach a non-iterable value.

So you should have a check if the value $_SESSION['item'] can actually be iterated:

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

     // Resto do seu código aqui
}

I have chosen to use isset , because if you use is_array directly, a E_NOTICE will be emitted if the 'item' of array does not exist.

    
03.11.2017 / 14:34