0

I have created a shortlist feature which acts a bit like a shopping cart. I output the items in the shortlist by:

$i = 0;
while ($i < $countArray){

echo $_SESSION['shortlistArray'][$i]." <a href='shortlistRemoveItem.php?arrayID=$i'>[x]</a><br />";

$i++;
}

and delete an item by

$arrayID = $_GET["arrayID"];
unset($_SESSION['shortlistArray'][$arrayID]);

The problem is that when I delete an item from an array such as $_SESSION['shortlistArray'][2] the output is all messed up as the array is no londer sequential. Should I recode the way my array is outputted or the way I am deleting an item from an array?

1
  • 1
    maybe you should use FOR instaad of WHILE? Also try to VAR_DUMP($_SESSION['shortlistArray']) to esure that is's ok before delete. Commented Sep 25, 2011 at 13:50

1 Answer 1

0

The most efficient solution would be simply changing the way your array is outputted:

foreach($countArray as $key => $item){

    echo $_SESSION['shortlistArray'][$key]." <a href='shortlistRemoveItem.php?arrayID=$key'>[x]</a><br />";
}

If you insist on changing the way you are deleting an item from the array, consider this alternative:

$arrayID   = $_GET["arrayID"];
$tempArray = array();

foreach($countArray as $key => $item){

    if($arrayID == $key) continue;
    $tempArray[] = $item;
}

$_SESSION['shortlistArray'] = $tempArray;

I' recommend the first option though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.