PHP delimited random number, non-repeating
P粉131455722
P粉131455722 2023-09-06 20:26:26
0
2
571

I have the following php code which creates random numbers when adding a static number ;100 and divides the number with |. It works fine but creates duplicate numbers, how do I make it prevent duplicate numbers from being created?

echo shd is 3;100|2;100, but there is no repeated number before ;100. But this code sometimes outputs numbers like 2;100|2;100, which are repeated.

<?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;

P粉131455722
P粉131455722

reply all(2)
P粉512526720

You can use array_unique to remove duplicates before the array implodes

$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;
P粉807397973
$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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template