helmet648
helmet648

Reputation: 53

how to change the value of a session array variable

i've looked and looked, and can't find out how to change a session variable and store it back into the array. my code does what i want so far, and adds 1 to the variable, but i don't know how to save it back into the array. my code is as follows.

if(isset($_GET['action']) && $_GET['action'] == 'addp')
{
echo "trying to add 1 item to serial ".$_GET['id']."<br>";
$product_code = filter_var($_GET['id'], FILTER_SANITIZE_STRING);
if(isset($_SESSION['products']))
{
    $number = 0;
    foreach($_SESSION['products'] as $cart_itm)
    {

        if($cart_itm['code'] == $product_code)
        {               
            $a = array($_SESSION['products']);
            foreach($_SESSION['products'] as $a){
                foreach($a as $b){
                    while(list($key, $val) = each($a)){
                        if($key == 'qty'){
                            $val = $val + 1;
                            echo $val;
                        }
                    }
                }
            }               

        }
        else
        {
            echo"Item Code Did not Match";
        }
        $number++;
    }
}
else
{
    echo"Session['Products'] Not Set";
}
}
else
{
    echo"Action is set to ".$_GET['action'];
}

Any help, even if its pointing me at a post I failed to look at would help.

Also, any pointers on code style would be appreciated.

Upvotes: 1

Views: 1473

Answers (3)

helmet648
helmet648

Reputation: 53

what i did to fix the situation

if(isset($_SESSION['products']))
{

$number = 0;

foreach($_SESSION['products'] as $cart_itm)
{
    if($cart_itm['code'] == $product_code)
    {               

        $_SESSION['products'][$number]['qty'] = $cart_itm['qty'] + 1;
    }
    else
    {
        echo"Item Code Did not Match";
    }
    $number++;
}

}

Upvotes: 0

Try this:

if(isset($_SESSION['products']))
{
    $number = 0;
    foreach($_SESSION['products'] as $cart_itm)
    {
        if($cart_itm['code'] == $product_code)
        {               
            $_SESSION['products']['qty']++; //here is the quantity of the item, no need of more loops
            echo $_SESSION['products']['qty'];
        }
        else
        {
            echo"Item Code Did not Match";
        }
        $number++;
    }
}

Upvotes: 0

Verhaeren
Verhaeren

Reputation: 1661

This should probably do:

if($key == 'qty'){
    $_SESSION['products'][$key] = $val + 1; //this line
    $val = $val + 1;
    echo $val;
}

If not, use the same concept: you have the key which allow you to specify which item in the array you want to change.

Upvotes: 1

Related Questions