php method that checks two strings in a variable

Asked

Viewed 31 times

0

Does anyone know any method in PHP that matches the value of a variable with string?

I need to refactor the following code:

 public function hasPlan() : bool
{
    return $this->reference === 'unico' || $this->reference === 'simultaneo';
}

I would like some tip that returns boolean and tell me that variable $reference is equal to single string or string' .

  • And what’s the problem with the current code so you need to refactor it?

  • no problems, but I think it can be improved.

  • If you had a PHP method that validated the string, like: method_php($Reference, [unico', 'simultaneo'])

  • Reminds me Overengineering , not always less code equals more performance.

1 answer

3


Apparently, you are considering that writing twice the variable is to insert redundancy into the code. On the one hand it is, but it makes the code simpler. If you still want to change, just use the native function in_array:

public function hasPlan() : bool
{
    return in_array($this->reference, ['unico', 'simultaneo']);
}
  • Perfect, exactly what I was looking for, because if more strings appear to be validated, this way it becomes more redundant.

  • Boy, what a good job, I didn’t know this one, I really enjoyed it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.