tags:

views:

35

answers:

3

I have a cookie which stores info in an array.

This is for a classifieds website, and whenever users delete their 'ads' the cookie must also be removed of the ad which was deleted.

So I have this:

if (isset($_COOKIE['watched_ads'])){
$expir = time()+1728000;
        $ad_arr = unserialize($_COOKIE['watched_ads']);
        foreach($ad_arr as $val){
            if($val==$id){  // $id is something like "bmw_m3_10141912"
                unset($val);
                            setcookie('watched_ads', serialize($ad_arr), $expir, '/');
            }
        }
        }

This doesn't work... any idea why? I think its a problem with the unset part... Also, keep in mind if there is only one value inside the array, what will happen then?

Thanks

A: 

array_filter seems appropriate:

$array = array_filter($array, create_function('$v', 'return $v != '.$id.';'));
knittl
+1  A: 

You got two bugs here: 1) you unset the $val instead of the array element itself. 2) You set the cookie within the loop to the unknown $ad_arr2 array.

    foreach($ad_arr as $key => $val){
        if($val==$id){  // $id is something like "bmw_m3_10141912"
            unset($ad_arr[$key]);
        }
    }
    setcookie('watched_ads', serialize($ad_arr), $expir, '/');
Matijs
A: 

You are correct that you are using unset incorrectly. The manual on unset states:

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

When you use 'as' you're assigning the value of that array element to a temporary variable. You want to reference the original array:

foreach ($ad_arr as $key => $val)
...
            unset($ad_arr[$key]);
...
Conspicuous Compiler
dnagirl
@dnagirl If you unset($value) in that case, you break the reference, but you do not remove the element from the array. You still need to reference the array in the unset.
Conspicuous Compiler
oops! true. I was thinking about how convenient it was for resetting (no more `array_walk()`!) and forgot the OP was about unsetting. `<blushing/>`
dnagirl