简体   繁体   中英

How to assign 2 variables with if statements in php?

I want to assign width and height variable for 3 different conditions. However, this doesn't work:

if ($d=="1") $w=100 ;$h=200;
if ($d=="2") $w=200 ;$h=300;
if ($d=="3") $w=200 ;$h=400;

How can I code it using php?

did you notice the "# etc" part ?

if($c1){
$w=200;
$h=100;
}

elseif($c2){
$w=300;
$h=200;
}

else{
$w=400;
$h=300;
}
if($c1){
    $w = 200;
    $h = 100;
}
# etc

From OP's comments, you are missing brackets, also make sure that your variable $d is string because comparing a string and integer will give unexpected results

if ($d=="1") { 
  $w=100 ;
  $h=200; 
} elseif ($d=="2") {
  $w=200 ;
  $h=300;
} elseif ($d=="3") { 
  $w=200 ;
  $h=400;
} else {
   //default values
}

I think switch case would better than if statement..

switch ($ch) {
case 1:
    $w=200px; 
    $h=100px;
    break;
case 2:
    $w=300px;
    $h=200px;
    break;
case 3:
    $w=400px ;
    $h=300px;
    break;

}

if($condition==1)
{
    $w=200;
    $h=100;
}else if($condition==2)
{
    $w=300;
    $h=200;
}else if($condition==3)
{ 
     $w=400;
     $h=300;
}
else
{
    //Other Data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM