Y
Y
Yuri Yerusalimsky2016-04-03 22:28:31
PHP
Yuri Yerusalimsky, 2016-04-03 22:28:31

How in PHP to make it more correct to execute a condition under many similar conditions?

Let's say I have a variable $a and it can be equal to several values, like "one", "two", "letter", "sun", "light", etc., just values ​​from my head. You need to make an if condition so that if $a is equal to one of the above values, then execute some code. I don't want to write a bunch of constructs like $a == "one" OR $a == "two" OR $a == "letter". I think, how would it be more correct to implement, so that a multi-ton code does not turn out. Such values ​​can be under 20 pieces, as it were. Multiline conditional code seems ugly to me. I think that you need to dig in the direction of creating an array with these values ​​and then check the presence of $a inside this array - am I right? If yes, I think to write here how I see the processing of the array.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kravchenko, 2016-04-03
@werber

$wordsArray = ['one','two','three'];
if(in_array($a,$wordsArray)){
  //code here
}

T
theg4sh, 2016-04-11
@theg4sh

Yes, using an array is one of the easiest ways.
But still, the construction from if will be faster - in the case of arrays, in addition to allocating memory for strings, memory will also be allocated for the array itself, also with deallocation.
On one condition, this is not noticeable, only on the scale of a large project, hundreds of extra memory allocation operations from each client are useless.
As an alternative to blocks from if - the switch-case construction:

switch($a){
case "one":
case "two":
case "three":
  // your code
}

If you are only looking for simple strings, you can use the strpos trick:
if (strpos(":"+$a+":", ":one:two:three:space ship:") !== FALSE) {
  // your code here
}

in this case, only one substring search cycle will be launched.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question