How can PHP developers efficiently check for and prevent duplicate entries in an array when adding new items to a shopping cart?

When adding new items to a shopping cart, PHP developers can efficiently check for and prevent duplicate entries by first checking if the item being added already exists in the cart. If it does, they can increment the quantity of that item instead of adding a new entry. This can be achieved by looping through the cart array and comparing the item IDs. If a duplicate is found, the quantity can be increased and the loop can be exited.

// Check if item already exists in the shopping cart
$newItem = [
    'id' => 123,
    'name' => 'Example Item',
    'price' => 10.99,
    'quantity' => 1
];

$found = false;
foreach ($cart as $key => $item) {
    if ($item['id'] === $newItem['id']) {
        $cart[$key]['quantity'] += $newItem['quantity'];
        $found = true;
        break;
    }
}

// If item is not found, add it to the shopping cart
if (!$found) {
    $cart[] = $newItem;
}