Jump to content

If OR


mcfmullen

Recommended Posts

<?php 
if (trim($table) == 'pigs' || 'sheep' || 'goats' || 'cows' || 'flamingoes'){
echo "blah blah blah";
} else {
echo "bleep bleep bleep";
?>

 

The code above doesn't work. It echoes blah blah blah no matter what $table is set to. How am I supposed to use OR during an If statement?

Link to comment
Share on other sites

That's because trim($table) == 'pigs' is evaluated first, then the result of that is OR'd with 'sheep' and the result of that is OR'd with 'goats' ... The result of which is always TRUE.

 

You would need to write out each comparison or since you are comparing one variable with a list of values, use the in_array function.

Link to comment
Share on other sites

$table = trim($table);
if ($table == 'pigs' || $table == 'sheep' || $table == 'goats' || $table == 'cows' || $table == 'flamingoes') {
   echo "blah blah blah";
} else {
   echo "bleep bleep bleep";
}

 

Or you can do something like:

$animals = array('pigs', 'sheep', 'goats', 'cows', 'flamingoes');

if(in_array(trim($table), $animals)) {
   echo "blah blah blah";
} else {
   echo "bleep bleep bleep";
}

Link to comment
Share on other sites

That's not how you write the condition, use

<?php
if (trim($table) == 'pigs' || trim($table) == 'sheep' || trim($table) == 'goats' || trim($table) == 'cows' || trim($table) == 'flamingoes'){
?>

or you can use a switch statement:

<?php
switch (trim($table)) {
    case 'pigs':
    case 'sheep':
    case 'goats':
    case 'cows':
    case 'flamingoes':
        echo 'blah blah blah blah';
        break;
   default:
        echo 'bleep bleep bleep';
}
?>

 

Ken

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.