3 回答
TA贡献1845条经验 获得超8个赞
我希望这就是你想要的
<?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";
}
?>
TA贡献1821条经验 获得超5个赞
我真的不明白你为什么要在switch这里使用声明。在改进代码方面 - 您只能使用 2 行。随着if和switch它的每个条件2-3行,它是最坏的编程习惯你可能会拿出。只要给我一个很好的理由,为什么。
如果您仔细阅读 PHP 文档,则可以使用字符串运算符页面,其中解释了如何解决您的问题:
连接运算符 ( .),它返回其左右参数的连接。
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
所以你可以简单地用
$rand = rand(1,10);
$profile_pic = "/defaults/profile_pic" . $rand . ".png";
或者你可能会偶然发现Variable parsing,它指出:
当一个字符串用双引号或 heredoc 指定时,变量在其中解析。
$juice = "apple";
echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
所以你可以做的是:
$rand = rand(1,10);
$profile_pic = "/defaults/profile_pic${rand}.png";
TA贡献1796条经验 获得超4个赞
如果您在图像路径中使用相同的随机数,则不需要 if 或 switch 循环。您可以使用以下代码。$rand = rand(1,10) ;
$profile_pic = "/defaults/profile_pic$rand.png"; 如果您有随机数和图像的映射,则将其存储在数组中并访问它。$rand_image = array(1=>"firstimg.png", 2=>"2.png") ;
$profile_pic = "/defaults/profile_pic".$rand_image[$rand];
- 3 回答
- 0 关注
- 347 浏览
添加回答
举报
