首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >做一个PHP切换的最好方法是不是每种情况都有多个值?

做一个PHP切换的最好方法是不是每种情况都有多个值?
EN

Stack Overflow用户
提问于 2009-08-21 01:52:38
回答 16查看 204.5K关注 0票数 76

如何执行此PHP switch语句?

还要注意的是,这些是小得多的版本,我需要创建的1将有更多的值添加到它。

版本1:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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 //数组

EN

Stack Overflow用户

发布于 2012-11-17 04:06:04

交换机与相结合将为您提供更大的灵活性:

代码语言:javascript
运行
复制
<?php
$p = 'home'; //For testing

$p = ( strpos($p, 'users') !== false? 'users': $p);
switch ($p) { 
    default:
        $varContainer = 'current_' . $p; //Stores the variable [$current_"xyORz"] into $varContainer
        ${$varContainer} = 'current'; //Sets the VALUE of [$current_"xyORz"] to 'current'
    break;

}
//For testing
echo $current_home;
?>

要了解更多信息,请查看variable variables和我提交给php手册的示例:

示例1http://www.php.net/manual/en/language.variables.variable.php#105293

示例2http://www.php.net/manual/en/language.variables.variable.php#105282

PS:这个示例代码是小而简单的,正是我喜欢的方式。它已经过测试,也可以正常工作

票数 0
EN
查看全部 16 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1309728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档