how to Ensure that it can not return one of the values in the array $ excluded.
This is my code
$exclus=array(1,4);
function ramdom(){
$resultat=rand(1,10);
return $resultat;
}
echo "Random Num : ".random()."
";
try this:
function randWithout($from, $to, array $exceptions) {
sort($exceptions); // lets us use break; in the foreach reliably
$number = rand($from, $to - count($exceptions)); // or mt_rand()
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++; // make up for the gap
} else /*if ($number < $exception)*/ {
break;
}
}
return $number;
}
and call it:
$exclus=array(1,4);
$random_number = randWithout(0,10,$exclus);
Here is an online demo of the code below: https://eval.in/87096
function ramdom() {
$resultat = rand(1,10);
$exclus = array(1,4);
if(in_array($resultat,$exclus)) {
return ramdom();
}
else {
return $resultat;
}
}
Use array_search
:
$exclus=array(1,4);
function random(){
$resultat=rand(1,10);
return array_search($resultat,$exclus) ? ramdom() : $resultat
}
<?php
$exclus = array(1,4);
function ramdom() {
$resultat = rand(1,10);
while(in_array($resultat, $exclus)) {
$resultat = rand(1,10);
}
return $resultat;
}
?>
Should work, but I didn't test it...