1

I have a multi dimensional array that I am able to loop through with a FOR loop and return the values to enter into the database. The problem comes in when the user deletes an item which I then take out of the $_SESSION[cart] array using unset. Specifically if it was line 2 in the cart I would use

unset($_SESSION[cart][2]);

Now I can no longer use the FOR loop because the values I use in the FOR loop have gaps in them.

The original array would be:

$_SESSION['cart'][1] $_SESSION['cart'][2] $_SESSION['cart'][3]

AFTER deleting line 2 from the cart(it can be any line this is an example):

$_SESSION['cart'][1] $_SESSION['cart'][3]

This is how the array is structured:

$_SESSION['cart'][$lineId] = array('stockNumber' => $stockNumber, 'description' => $description, 'masterPrice' => $masterPrice);

$lineId is the line item in the cart

I currently retrieve the data from the cart using this loop:

for ($i = 1, $howMany = count($_SESSION['cart']); $i < $howMany+1; ) {
$stk_code = $_SESSION['cart'][$i]["stockNumber"];
$description = $_SESSION['cart'][$i]["description"]; 
$unitPrice = $_SESSION['cart'][$i]["masterPrice"];}

I need help in understanding this and a way to loop through the array regardless of line item number. I have no way of knowing how many items will be in the cart or how many they take out. Any help would be appreciated.

2
  • 2
    foreach perhaps. Commented Oct 5, 2016 at 3:06
  • after deleting if you make your $_SESSION['cart'] array to array_values($_SESSION['cart']) and try.... it will re-index your array.. Commented Oct 5, 2016 at 3:06

1 Answer 1

1

You can use foreach instead of for loop

$_SESSION['cart'][1] = array('stockNumber' => 1, 'description' => 'test', 'masterPrice' => 115);

    foreach ($_SESSION['cart'] as $value) {
      $stk_code = $value["stockNumber"];
      $description = $value["description"]; 
      $unitPrice = $value["masterPrice"];
    }
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.