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;
}
精彩评论