Richard Hedges
Richard Hedges

Reputation: 1188

Remove an item from an array?

I've created an array from a PHP session variable, and now I'm trying to use ajax (within jQuery) to remove an element from the array.
I've got the following code so far:

$val = $_SESSION['enquiry-basket'];
$array = explode($val);

foreach ($enquiries as $a => $q) {
    if ($q == $_POST['product_id']) {
        unset($array[$a]);
    }
}

The only problem is, it doesn't remove the item.
Can anyone explain why, and tell me how to fix it?

Edit

Sorry guys. The reason I mentioned jQuery is because I use a jQuery ajax call to process the PHP I displayed above.
The ajax query runs fine because it processes some javascript goodies (remove's a div from the HTML) once the ajax returns a success.
I've added the delimiter (can't believe I missed it) but the element doesn't get removed from the array still.
I've never been good at multi-dimensional arrays, so here's the array printed:

Array ( [0] => 6 [1] => 8 ) 

It looks right to me, but I'm an amateur in arrays. (6 and 8 are of course my strings I inserted)

Upvotes: 1

Views: 739

Answers (5)

Vimalnath
Vimalnath

Reputation: 6463

Mostly an issue with the explode function, the second parameter is missing:

Change from:

$array = explode($val);

To:

$array = explode('~',$val);  // ~ is a delimiter

Upvotes: 1

xCander
xCander

Reputation: 1337

explode is missing the first argument:

explode(',', $val);

Upvotes: 8

Sylver
Sylver

Reputation: 8968

If I understand correctly what you are trying to do, the problem is that JQuery runs client side, which means that your PHP arrays on the server side disappear between each request from Ajax. The only array that remains is $_SESSION.

If you want to use AJAX, you need to remove from $_SESSION directly. Anything else is just useless because the arrays and variables "disappear" between each call.

Upvotes: 1

chella
chella

Reputation: 164

The explode function should have two parameters. But you given only the name of the array. explode(separator,string,limit);

Upvotes: 1

Marcin Zaluski
Marcin Zaluski

Reputation: 725

You are removing item from $array, not from $_SESSION['enquiry-basket'].

Upvotes: 2

Related Questions