Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php if and elseif statements with multiple/more than 3 conditions [closed]

I want to assign random profile pictures to users when they register on a website. I have a problem with my code. If I limit the "if and elseif" statements to 2 conditions, it works well. But when I go over 2 (in this case I have 10 conditions), the code doesn't work. If "switch" statement should be used instead, how would you write the code?

Here is my code

$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";
like image 490
Shea Avatar asked Dec 28 '25 15:12

Shea


1 Answers

I hope that's what you want

<?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";
}
?>
like image 72
Wassim Al Ahmad Avatar answered Dec 30 '25 15:12

Wassim Al Ahmad