user3244842
user3244842

Reputation:

Simplify PHP multiply if conditions

I wonder is there any way to make this code more subtle?

Ex

 public function hookDisplayHeader()
{
    if(Tools::getValue('controller')=='index'){
        $this->context->controller->addCSS(($this->_path).'something.css', 'all');
    }
    if(Tools::getValue('controller')=='cms'){
        $this->context->controller->addCSS(($this->_path).'something.css', 'all');
    }
    if(Tools::getValue('controller')=='product'){
        $this->context->controller->addCSS(($this->_path).'something.css', 'all');
    }
    if(Tools::getValue('controller')=='category'){
        $this->context->controller->addCSS(($this->_path).'something.css', 'all');
    }

}

to simple

 public function hookDisplayHeader()
     {
         if(Tools::getValue('controller')=='index AND product AND cms AND category'){
        $this->context->controller->addCSS(($this->_path).'something.css', 'all');
         }
     }

this code not work :(

Upvotes: 0

Views: 128

Answers (2)

Rimble
Rimble

Reputation: 893

Use in_array();

public function hookDisplayHeader()
{
    $values = array('index','cms','product','category');
    if(in_array(Tools::getValue('controller'), $values)){
        $this->context->controller->addCSS(($this->_path).'something.css', 'all');
    }
}

Upvotes: 2

Jim
Jim

Reputation: 22646

I would place them in an array and check that:

$somethingCSSControllers = array('index','product','cms','category');

if(in_array(Tools::getValue('controller'),$somethingCSSControllers)){
    $this->context->controller->addCSS(($this->_path).'something.css', 'all');
}

Upvotes: 1

Related Questions