Andy Ward Andy Ward - 6 months ago 10
PHP Question

Do not add an item to a session array if it already exists

Hi I am a bit of a newbie here - so please bear with me.
I am trying to create a WishList - similar to a shopping cart but without the payment gateway. Anyway.

I have the following code which adds an item to an array when the Add to Wishlist button is clicked

if (isset($_GET['add'])){
$ITEM = array(
'name' => $_GET['add']
);
{
$_SESSION['WISH_LIST'][] = $ITEM;
header('Location: ' . $_SERVER['PHP_SELF']);
}
}


I want to make it work so that the item is not added if it is already there.

I tried this

if (isset($_GET['add'])){
$ITEM = array(
'name' => $_GET['add']
);

if ( in_array($_GET['add'], $ITEM) )
{
echo "Already Added";
}
else
{
$_SESSION['WISH_LIST'][] = $ITEM;
header('Location: ' . $_SERVER['PHP_SELF']);
}
}


But this never adds the item - I always get the 'Already Added' text.

Answer

You need to check what exists in the session, not the $ITEMS array:

if (isset($_GET['add'])) {
    $ITEM = array(
        'name' => $_GET['add']
    );

    if (in_array($ITEM, $_SESSION['WISH_LIST'])) {
        echo "Already Added";
    } else {
        $_SESSION['WISH_LIST'][] = $ITEM;
        header('Location: ' . $_SERVER['PHP_SELF']);
    }
}

It might be nicer to indent your code, too.