Skip to content
Advertisement

PHP – Multiple OR operators in if statement

I am working with getters and setters within my Symfony project. I have to use if() statement to check if status field does not have specific values before changing other field.

Code:

const STATUS_FAILED = 'failed';
const STATUS_PROGRESS = 'progress';
const STATUS_DELETED = 'deleted';

if ($entity->getStatus() !== Entitiy::STATUS_FAILED || 
    $entity->getStatus() !== Entitiy::STATUS_PROGRESS || 
    $entity->getStatus() !== Entitiy::STATUS_DELETED) 
    {
        $entity->setPreviousStatus($entity->getStatus());
    }

I defined constants and also using OR operator. I was wondering if there is more elegant solution than this. Maybe is_array() function, but don’t know can it be used in this contest?

Advertisement

Answer

I think you should do something like this

 $allowed = [self::STATUS_DELETED, self::STATUS_PROGRESS, self::STATUS_FAILED];
 if(!in_array($entity->getStatus(), $allowed)) {
     $entity->setPreviousStatus($entity->getStatus());
 }

Passing your constants in an array and the check if you status is in_array.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement