如何执行此PHP switch语句?
还要注意的是,这些是小得多的版本,我需要创建的1将有更多的值添加到它。
版本1:
switch ($p) { 
    case 'home': 
    case '': 
        $current_home = 'current';
    break; 
    case 'users.online': 
    case 'users.location': 
    case 'users.featured': 
    case 'users.new': 
    case 'users.browse': 
    case 'users.search': 
    case 'users.staff': 
        $current_users = 'current';
    break;
    case 'forum': 
        $current_forum = 'current';
    break; 
} 版本2:
switch ($p) { 
    case 'home': 
        $current_home = 'current';
    break; 
    case 'users.online' || 'users.location' || 'users.featured' || 'users.browse' || 'users.search' || 'users.staff': 
        $current_users = 'current';
    break;
    case 'forum': 
        $current_forum = 'current';
    break; 
} 更新-测试结果
我在10,000次迭代中运行了一些速度测试,
Time1: 0.0199389457703 // If语句
Time2: 0.0389049446106 //开关语句
Time3: 0.106977939606 //数组
发布于 2009-08-21 02:50:13
对于任何情况,如果你有一个未知的字符串,并且你需要找出它与一堆其他字符串中的哪一个匹配,唯一不会随着你添加更多项而变得更慢的解决方案是使用一个数组,但将所有可能的字符串作为键。因此,您的交换机可以替换为以下内容:
// used for $current_home = 'current';
$group1 = array(
        'home'  => True,
        );
// used for $current_users = 'current';
$group2 = array(
        'users.online'      => True,
        'users.location'    => True,
        'users.featured'    => True,
        'users.new'         => True,
        'users.browse'      => True,
        'users.search'      => True,
        'users.staff'       => True,
        );
// used for $current_forum = 'current';
$group3 = array(
        'forum'     => True,
        );
if(isset($group1[$p]))
    $current_home = 'current';
else if(isset($group2[$p]))
    $current_users = 'current';
else if(isset($group3[$p]))
    $current_forum = 'current';
else
    user_error("\$p is invalid", E_USER_ERROR);这看起来不像switch()那样干净,但它是唯一一个快速的解决方案,它不包括编写一个小的函数和类库来保持它的整洁。将项添加到数组中仍然非常容易。
发布于 2009-08-21 02:19:46
版本2不起作用!!
case 'users.online' || 'users.location' || ...完全等同于:
case True:对于$p的任何值,都将选择该case,除非$p为空字符串。
||在case语句中没有任何特殊含义,您不会将$p与这些字符串中的每一个进行比较,您只是检查它是否不是False。
发布于 2009-08-21 02:11:04
将这些值放入数组并查询数组,因为switch-case似乎隐藏了当字符串变量用作条件时您试图实现的底层语义,从而使其更难阅读和理解,例如:
$current_home = null;
$current_users = null;
$current_forum = null;
$lotsOfStrings = array('users.online', 'users.location', 'users.featured', 'users.new');
if(empty($p)) {
    $current_home = 'current';
}
if(in_array($p,$lotsOfStrings)) {
    $current_users = 'current';
}
if(0 === strcmp('forum',$p)) {
    $current_forum = 'current';
}https://stackoverflow.com/questions/1309728
复制相似问题