user5286438
user5286438

Reputation:

Is there a way to check whether a value equals 0 or 1, with a single comparison?

I have a lot of pieces of code like

    case 'add':
    {   
        $succeeded = $wpdb->insert('coms', 
                                   array('name'=>$name,'story'=>$story,'imgurl'=>$imgurl)
                                   ) === 1;
        break;
    }

and I just realized that I need to change them all to compare against both 1 and 0. They would all be like

        $numRowsAffected = $wpdb->insert('coms', 
                                   array('name'=>$name,'story'=>$story,'imgurl'=>$imgurl)
                                   );
        $succeeded = $numRowsAffected === 1 || $numRowsAffected === 0;

HOWEVER, I'm wondering whether there is a more compact, elegant and efficient way of checking a value against 1 or 0. Can I do it in one fell swoop with bitshift operators?

Upvotes: 1

Views: 115

Answers (3)

You can check whether variable & 0b1111111111111110 is zero, where you adapt the lenght of the bit pattern to the maximum size of the variable.

Upvotes: 0

Tony Vance
Tony Vance

Reputation: 134

if ($value | 1 === 1)

I think that should do the trick.

Upvotes: 4

taxicala
taxicala

Reputation: 21759

You can use in_array:

$succeeded = in_array($numRowsAffected, array(0, 1));

Upvotes: 1

Related Questions