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粉5125267202023-09-07 14:36:59
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粉8073979732023-09-07 11:50:21
$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