简体   繁体   English

任何减少php中代码重复模式的方法

[英]Any ways to reduce the repeated patterns of code in 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;
}

Is there any way to prevent repeating $brand == "xxx"?? 有什么方法可以防止重复$ brand ==“ xxx”?

是的,您可以使用in_array

in_array($brand, array('Kumiai bla', 'Analblah', 'Whatever', ...))

You can create an associative array: 您可以创建一个关联数组:

$brands = array(
    "Kumiai Dairies" => true,
    "Anlene" => true,
    ...
);

and then check it with 然后用

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

}

See @Corbin's comment at @ThiefMaster's answer for an explanation of the the differences of these two approaches. 有关这两种方法的区别的解释,请参见@ThiefMaster答案上的@Corbin评论。

You can use switch, 1.its fast, search is const time 2.don't need to create array & search in it every time. 您可以使用switch,1。其速度快,搜索时间为常量时间。2。无需每次创建数组并在其中搜索。

switch($brand){
case "Kumiai Dairies":
case "Anlene":
....
....
//do something
break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM