madeye
madeye

Reputation: 1406

Better Way of Writing If else statement

Is there any better way of writing this:

if (in_array('WIN_WAITING', $statuses)) {
    $this->globalStatus = 'WIN_WAITING';
} else if (in_array('IN_PLAY', $statuses)) {
    $this->globalStatus = 'IN_PLAY';
} else if (in_array('WON', $statuses)) {
    $this->pay($this->tickets['ticketID']);
    $this->globalStatus = 'WON';
} else if (in_array('PAYEDOUT', $statuses)) {
    $this->globalStatus = 'PAYEDOUT';
} else if (in_array('CLOSED', $statuses)) {
    $this->globalStatus = 'CLOSED';
} else if (in_array('LOST', $statuses)) {
    $this->globalStatus = 'LOST';
} else if (in_array('OPEN', $statuses)) {
    $this->globalStatus = 'OPEN';
}

Upvotes: 1

Views: 81

Answers (2)

Jackerbil
Jackerbil

Reputation: 140

Maybe something like

$options = array('WIN_WAITING', 'IN_PLAY', 'WON', 'PAYEDOUT', 'CLOSED', 'LOST', 'OPEN');

for($i=0; $i<=7; $i++) {

 if(in_array($options[$i], $statuses)) {
   $this->globalStatus = $options[$i];
   break;
 }

}

Not tested, just an idea

Upvotes: 2

Rizier123
Rizier123

Reputation: 59701

This should work for you:

(Here I just loop through all of your search strings and if I found it I break out the loop)

<?php

    $search = ["WIN_WAITING", "IN_PLAY", "WON", "PAYEDOUT", "CLOSED", "LOST", "OPEN"];

    foreach($search as $v) {
        if(in_array($v, $statuses)) {
            if($v == "WON") $this->pay($this->tickets['ticketID']);
            $this->globalStatus = $v;
            break;
        }

    }

?>

Upvotes: 3

Related Questions