Hi all,

I'm trying to delete elements from an array - The array should be a shopping cart - So I need to ad/remove items from it.

So far I can add items no problem, but i seem to keep failing to delete the correct indexes.

The array contains a product id and the quantity of that product in the cart.

I have this:

// Cart array:
// Should that be build in another way?
$cart = array( 'data' => array( 'product_id' => array( 1000 ), 'quantity' => array( 1 ) ) );

print_r( $cart );
echo '<br /><br />';

// Add items to the cart:
array_push( $cart['data']['product_id'], 2000 );
array_push( $cart['data']['quantity'], 2  );

print_r( $cart );
echo '<br /><br />';

// Variable with the item to delete from the cart:
$id = 1000;

// Variable to hold the length of the items in the cart
$max = count( $cart['data'] );

// Loop through the cart, and see if the id is there, and if it is, then delete $cart[$i] ?
for( $i = 0; $i < $max; $i++ )
{
foreach( $cart as $key => $value )
{
    echo $value['product_id'][$i] . '<br />';
    echo $value['quantity'][$i] . '<br />';
    // Tjek om id er i array, og slet det hvis det er:
    if( in_array( $id, $value['product_id'] ) )
    {
        echo '<p>Match!</p>';
        echo $value['product_id'][$i];
    }
}

/*
if( in_array( $id, $cart['data']['product_id'] ) )
{
    echo 'Found<br />';
    unset( $cart[$i] );
}
*/
}

echo '<br /><br />';
print_r( $cart );

How can I go about this?

/Klemme

overwrite line 16 (above) with this:-

$id = 1000;

$key = array_search($id, $cart['data']['product_id']);
if($key!==FALSE) {
    unset($cart['data']['product_id'][$key]);
    unset($cart['data']['quantity'][$key]);
}
print_r($cart);
die;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.