phparraysrandomduplicates

How to ensure that randomly fetched values are never duplicated in an array


On a product page I want to show 4 other products selected randomly, but never the product that is already being displayed. The product id of the displayed one is $_product->getId() and all the products go into a $result[] array like this:

foreach ($collection as $product) {
    $result[]=$product->getId();
}

I'm using $need = array_rand($result, 4); to get the ids of the 4 random products, but it might include the id of the product on display. How do I exclude $_product->getId() from the $need[] array?


Solution

  • Don't put id of the product you don't want to show into $result:

    $currentProductId = $_product->getId();
    foreach ($collection as $product) {
      if ($product->getId() != $currentProductId) $result[] = $product->getId();
    }