php - 每个案例使用多个值进行 PHP 切换的最佳方法是什么?

标签 php switch-statement

你会怎么做这个 PHP switch 语句?

另外请注意,这些版本要小得多,我需要创建的版本将添加更多的值。

版本 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 次迭代进行了一些速度测试,

时间 1: 0.0199389457703//If 语句
时间2:0.0389049446106//switch语句
时间 3:0.106977939606//数组

最佳答案

对于您有一个未知字符串并且您需要找出它与一堆 other 字符串中的哪一个匹配的任何情况,这是唯一不会随着您添加更多字符串而变慢的解决方案items 是使用数组,但将所有可能的字符串作为键。因此,您的开关可以替换为以下内容:

// 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() 那样干净,但它是唯一的fast 解决方案,它不包括编写一个小的函数和类库保持整洁。向数组中添加项目仍然非常容易。

关于php - 每个案例使用多个值进行 PHP 切换的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1309728/

相关文章:

php - 使用 javascript 和 php 显示日历

php - Mysql 使用 Php foreach 循环选择并插入到另一个表中

java - 如何a=3和b=4?

java - 将线程与 paint java 一起使用

php - codeigniter 的哪个 ORM?

PHP图片上传功能,保存到一个目录,然后返回保存图片的url

php - 在 PHP 中将对象转换为整数

java - 我将如何比较两个将转换为相同字符的字符?

java - 为什么不使用 switch case 语句?

php - 使用特定的 CSS 加载 HTML 文件