Jump to content

short way of writing if OR OR OR OR statement?


wfcentral

Recommended Posts

there must be a shorter way of writing this... it is just a portion of the code I'm using and it's only going to get longer...

 

if ($row['label']=='Family Attraction') {$color='ORANGE';}

if ($row['label']=='Museum') {$color='ORANGE';}

if ($row['label']=='Arts') {$color='ORANGE';}

if ($row['label']=='Landmark') {$color='ORANGE';}

if ($row['label']=='Italian') {$color='RED';}

if ($row['label']=='Greek') {$color='RED';}

if ($row['label']=='Steak') {$color='RED';}

if ($row['label']=='Seafood') {$color='RED';}

I see three options:

 

You could combine the options:

<?php

if ($row['label']=='Family Attraction' || $row['label']=='Museum')
    || $row['label']=='Arts' || $row['label']=='Landmark') {
    $color='ORANGE';
}

if ($row['label']=='Italian' || $row['label']=='Greek'
   || $row['label']=='Steak' || $row['label']=='Seafood') {
    $color='RED';
}

?>

 

You could use a switch which is better programatically, but not shorter

 

<?php

switch ($row['label']) {

    case 'Family Attraction':
    case 'Museum':
    case 'Arts':
    case 'Landmark':
        $color = 'ORANGE';
        break;

    case 'Italian':
    case 'Greek':
    case 'Steak':
    case 'Seafood':
        $color = 'RED';
        break;
}

?>

 

Or you could use an array:

 

<?php

$colors = array (
   'Family Attraction' => 'ORANGE',
   'Museum' => 'ORANGE',
// etc..
}

$color = $colors[$row['label']];

?>

 

Which one I would use would depend upon how often the list changes, how big the list is, etc. But, without more information I would suggest using the switch() statement.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.