什么是最快最有效的比较方法(PHP)

时间:2018-04-25 08:22:48

标签: php performance

我想知道比较最快捷,最有效的方法是什么。 这对我的代码更有意义:

public function exampleChangeVariable ($variable) {

  if ($variable == 'notif_received_title') {
    $variable = _('Text 1');
  }
  else if ($variable == 'notif_inprogress_title') {
    $variable = _('Text 2');
  }
  else if ($variable == 'notif_preparation_title') {
    $variable = _('Text 3');
  }
  else if ($variable == 'notif_positif_title') {
    $variable = _('Text 4');
  }
  else if ($variable == 'notif_negatif_title') {
    $variable = _('Text 5');
  }
  else if ($variable == 'notif_accepted_title') {
    $variable = _('Text 6');
  }
  else if ($variable == 'notif_rejected_title') {
    $variable = _('Text 7');
  }

  return $variable;
}

此功能位于foreach(数据库中恢复的数据)中,我希望将其优化到最大值。

  • 我应该使用数字作为变量吗?

  • 如果我想使用文本变量,长度重要吗? (notif_received_title将为received

  • else if是个不错的选择?

  • 我怎么能做得更好? (知道他可以有大约二十if

1 个答案:

答案 0 :(得分:3)

实际上,我只是创建一个关联数组并获取正确的索引。

您的代码将变为:

public function exampleChangeVariable($variable)
    {

        $assoc = [
            'notif_received_title'    => 'Text 1',
            'notif_inprogress_title'  => 'Text 2',
            'notif_preparation_title' => 'Text 3',
            'notif_positif_title'     => 'Text 4',
            'notif_negatif_title'     => 'Text 5',
            'notif_accepted_title'    => 'Text 6',
            'notif_rejected_title'    => 'Text 7'
        ];

        if (array_key_exists($variable, $assoc)) {
            return $assoc[$variable];
        }

        return null;

    }

虽然仍有改进的余地(因为按键具有相似的模式)

相关问题