Php 函数的作用是:返回一个从1到10的整数

Php 函数的作用是:返回一个从1到10的整数,php,Php,如何确保它不能返回其中一个值​​在数组中,$excluded 这是我的密码 $exclus=array(1,4); function ramdom(){ $resultat=rand(1,10); return $resultat; } echo "Random Num : ".random()."\n"; 试试这个: function randWithout($from, $to, array $exceptions) { sort($exceptions); // l

如何确保它不能返回其中一个值​​在数组中,$excluded

这是我的密码

$exclus=array(1,4);
function ramdom(){
   $resultat=rand(1,10);
   return $resultat;
}

echo "Random Num : ".random()."\n";
试试这个:

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

下面是代码的在线演示:

使用数组搜索:

?>


应该可以,但我没有测试它…

它不是一个随机调用,正如您在代码中定义的那样,它是如何工作的:它选择一个随机数,并检查它是否是禁止的数之一。如果是,则选择一个新的;如果没有,它将返回。它不能正常工作。如果您有1到5glad中的exeption 2,3,4可以帮助您:@user3172273i无法发布。。你能帮我做最后一件吗。。真的很感激,我应该如何更改代码以查找像22这样的数字,并且元素是字符串,因为20和12不应该被找到?这是我的代码$list=arrayc12,33,620b,22,31;函数cherche$dans,$quoi{foreach$dans as$item{if$item===$quoi{return trouvé$quoi;}}return pas trouvé$quoi;}echo cherche$list,12;回声\n;echo cherche$list,22;回声\n;echo cherche$list,20;好吧,对于这个问题,我建议你创建另一个问题来很好地描述这个问题,我将尝试解决它@user3172273@user3172273你试过这个吗?
$exclus=array(1,4);
$random_number = randWithout(0,10,$exclus);
function ramdom() {
   $resultat = rand(1,10);    
   $exclus = array(1,4);
   if(in_array($resultat,$exclus)) {
      return ramdom();
   }
   else {
     return $resultat;
  }
}
$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;
}