我想在用户注册网站时为其分配随机个人资料图片。我的代码有问题。如果我将“if 和 elseif”语句限制为 2 个条件,则效果很好。但是当我超过 2 个条件时(在本例中我有 10 个条件),代码就不起作用了。如果应该使用“switch”语句来代替,您将如何编写代码?
这是我的代码
$rand = rand(1,10); //random number between 1 and 10
if($rand == 1)
$profile_pic = "/defaults/profile_pic1.png";
else if($rand == 2)
$profile_pic = "/defaults/profile_pic2.png";
.
.
.
else if($rand == 9)
$profile_pic = "/defaults/profile_pic9.png";
else
$profile_pic = "/defaults/profile_pic10.png";
最佳答案
我希望这就是你想要的
<?php
$rand = rand(1,10);
switch ($rand) {
case "1":
$profile_pic = "/defaults/profile_pic1.png";
echo "1";
break;
case "2":
$profile_pic = "/defaults/profile_pic2.png";
echo "2";
break;
case "3":
$profile_pic = "/defaults/profile_pic3.png";
echo "3";
break;
case "4":
$profile_pic = "/defaults/profile_pic4.png";
echo "4";
break;
case "5":
$profile_pic = "/defaults/profile_pic5.png";
echo "5";
break;
case "6":
$profile_pic = "/defaults/profile_pic6.png";
echo "6";
break;
case "7":
$profile_pic = "/defaults/profile_pic7.png";
echo "7";
break;
case "8":
$profile_pic = "/defaults/profile_pic8.png";
echo "8";
break;
case "9":
$profile_pic = "/defaults/profile_pic9.png";
echo "9";
break;
case "10":
$profile_pic = "/defaults/profile_pic10.png";
echo "10";
break;
default:
$profile_pic = "/defaults/profile_picDEFAULT.png";
echo "default PHOTO";
}
?>
关于php if 和 elseif 语句具有多个/超过 3 个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57830039/