1

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

3 Answers 3

7

Yes, you can use in_array:

in_array($brand, array('Kumiai bla', 'Analblah', 'Whatever', ...)) 
Sign up to request clarification or add additional context in comments.

3 Comments

It's insignificant in this situation, but it might be worth mentioning to the OP that in_array is a linear search and array_key_exist (or isset on a key) is constant time. Sometimes I use Felix's approach if it's a large array that is being frequently searched.
@red23jordan: A linear search takes O(n) time to find an element. If you have an array with 1000 elements, you have to make 1000 comparisons (in the worst case). Finding an element in a hash table like data structure takes O(1), so it is independent of the size of your set. For small sets, like yours, the difference is negligible.
An associative array in PHP is essentially a hash table. Looking up a value in a hash table is a constant time operation (or... constant-ish). Hash tables map a key to a slot. in_array though has to do a linear search on all of the values because there's no quick way to find a value based on something else. (If the array were sorted or something, a binary search, or something better than a linear search could be done, but hash table will still always win.) Edit: Felix beat me to it :). Gonna leave it though because it's worded a bit different.
6

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.

2 Comments

You could probably make the array definition much nicer by using a regular array and then array_flip() it.
array_flipping will be done in linear time, though, so flipping will only be useful if the search is going to be done multiple times in the same script run.
1

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.