skip to Main Content

I have php code below that creates random numbers when adding static number ;100 and divides numbers with |. It works well but creates duplicate numbers, how to make it prevent creating duplicate numbers?

echo shd be 3;100|2;100 but without duplicate numbers before ;100. but this code outputs numbers like 2;100|2;100 sometimes, that are duplicates.

<?php
$kat_list=array(1,2,3,4);

$count_cat= rand(2,3);

for ($i = 1; $i <= $count_cat; $i++) {
    $rnd_cat= rand(0,count($kat_list)-1);
    $kats[]=$kat_list[$rnd_cat].'--100';

}
$line=implode('-',$kats);

 $line=str_replace('--', ';', $line);
 $line=str_replace('-', '|', $line);
 


 echo $line;

2

Answers


  1. You can use array_unique to remove duplicates before you implode the array

    $kat_list=array(1,2,3,4);
    
    $count_cat= rand(2,3);
    
    for ($i = 1; $i <= $count_cat; $i++) {
        $rnd_cat= rand(0,(count($kat_list)-1));
        $kats[]=$kat_list[$rnd_cat].'--100';
    
    }
    
    $kats = array_unique($kats);
    
    $line=implode('-',$kats);
    
    $line=str_replace('--', ';', $line);
    $line=str_replace('-', '|', $line);
     
     echo $line;
    
    Login or Signup to reply.
  2. $kat_list=array(1,2,3,4);
    shuffle($kat_list); // shuffle list
    $count=3;
    for($i=0; $i<$count; ++$i) {
        // get the first N items of the shuffled list
        printf("%d ", $kat_list[$i]);
    }
    

    Try it: https://3v4l.org/a31pv

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search