How can you prevent duplicate entries when sorting products by price in PHP?

When sorting products by price in PHP, one way to prevent duplicate entries is to use a multidimensional array to store both the product price and its corresponding details. By using the product price as the key in the array, you can ensure that each product is unique and prevent duplicates from being included in the sorted list.

// Sample array of products with prices
$products = [
    ['name' => 'Product A', 'price' => 50],
    ['name' => 'Product B', 'price' => 30],
    ['name' => 'Product C', 'price' => 50],
    ['name' => 'Product D', 'price' => 40]
];

// Sort products by price
usort($products, function($a, $b) {
    return $a['price'] <=> $b['price'];
});

// Create a new array to store unique products by price
$uniqueProducts = [];

foreach ($products as $product) {
    $price = $product['price'];
    
    // Check if product with the same price already exists
    if (!isset($uniqueProducts[$price])) {
        $uniqueProducts[$price] = $product;
    }
}

// Output unique products sorted by price
foreach ($uniqueProducts as $product) {
    echo $product['name'] . ' - $' . $product['price'] . PHP_EOL;
}