Any ways to reduce the repeated patterns of code in php

red*_*dan 1 php

I have some codes here

if ($brand == "Kumiai Dairies" || $brand == "Anlene" || $brand == "Yoplait" || $brand == "Hokkaido Hidaka" 
|| $brand == "Jacob's" || $brand == "V8" || $brand == "Cow & Gate"){
do something here;
}
Run Code Online (Sandbox Code Playgroud)

Is there any way to prevent repeating $brand == "xxx"??

Thi*_*ter 7

是的,你可以使用in_array:

in_array($brand, array('Kumiai bla', 'Analblah', 'Whatever', ...))
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下它是微不足道的,但是可能值得一提的是,in_array是一个线性搜索,而array_key_exist(或一个键上的isset)是恒定时间.有时我会使用Felix的方法,如果它是一个经常搜索的大型数组. (4认同)

Fel*_*ing 6

您可以创建一个关联数组:

$brands = array(
    "Kumiai Dairies" => true,
    "Anlene" => true,
    ...
);
Run Code Online (Sandbox Code Playgroud)

然后检查它

if(isset($brands[$brand])) {

}
Run Code Online (Sandbox Code Playgroud)

请参阅@Corbin在@ThiefMaster答案中的评论,以解释这两种方法的不同之处.