vendredi 6 septembre 2019

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

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

Aucun commentaire:

Enregistrer un commentaire