這個php判斷要怎麼簡寫比較好?

if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else if($nowSelf=='/x.php'){
  $real_title = $x;
}else{
  $real_title = '';
}

這個判斷要怎麼簡寫才好?

MM们
浏览 442回答 5
5回答

GCT1015

用Switch switch ($nowSelf) { case '/x.php': $real_title = $x; break; case '/x.php': $real_title = $x; break; default: # code... break; }

汪汪一只猫

$arr = new Array( 'default' => $default_title '/x.php' => $x, ... => .. ); // 很久没写 PHP 了,不知道如果 key 不存在是会报错还是怎样 // 或者你也可以用 for 循环找到匹配的 $title,否则使用默认 $arr['default'] $title = $arr[$nowSelf];

蝴蝶刀刀

$arr = [ '/x.php' => 'x', '/y.php' => 'y', '/z.php' => 'z', ] $title = !isset($arr[$nowSelf])?'':$arr[$nowSelf];

慕的地10843

个人推荐使用 switch switch (variable) { case 'value': # code... break; default: # code... break; }

茅侃侃

$arr = [ '/x.php' => 'x', '/y.php' => 'y', '/z.php' => 'z', ]; $real_title = $arr[$nowSelf] ?? 'Your default value';
打开App,查看更多内容
随时随地看视频慕课网APP