开发者

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"??


Yes, you can use 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.


You can use switch, 1.its fast, search is const time 2.don't need to create array & search in it every time.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜