Dan Goodspeed
Dan Goodspeed

Reputation: 3560

Is there a way to refactor multiple similar PHP ternaries?

I had some code that felt like had a lot of repetition in it. I got it down to the following chunk, but I still see a handful of things being repeated and it feels like there should be a cleaner way to write it. Is there anything more that can be done or is this it?

$w1 = ($fin[57] > $fin[60]) ? $tc[57] : $tc[60];
$l1 = ($fin[57] > $fin[60]) ? $tc[60] : $tc[57];
$w2 = ($fin[58] > $fin[59]) ? $tc[58] : $tc[59];
$l2 = ($fin[58] > $fin[59]) ? $tc[59] : $tc[58];

What I'd really like is if there was a way to get the ternary to return an array of the true and false values. Something like this fictitious code:

list($w1, $l1) = (array) ($fin[57] > $fin[60]) ? $tc[57] : $tc[60];
list($w2, $l2) = (array) ($fin[58] > $fin[59]) ? $tc[58] : $tc[59];

Upvotes: 1

Views: 56

Answers (2)

Jeto
Jeto

Reputation: 14927

I believe the shortest you could do without a function is this, but there's still a quite a bit of repetition:

[$w1, $l1] = $fin[57] > $fin[60] ? [$tc[57], $tc[60]] : [$tc[60], $tc[57]];

You could also do a very small function using PHP 7.4's short closures, if you're using that (the PHP < 7.4 version is closer to the other answer):

$wlValues = fn($i, $j) => $fin[$i] > $fin[$j] ? [$tc[$i], $tc[$j]] : [$tc[$j], $tc[$i]];

Usage:

[$w1, $l1] = $wlValues(57, 60);

Upvotes: 1

Anonymous
Anonymous

Reputation: 12017

You can use list to make it a little better:

$order = function ($i1, $i2) use ($fin, $tc) {
    $r = [$tc[$i1], $tc[$i2]];
    if ($fin[$i2] > $fin[$i1]) $r = array_reverse($r);
    return $r;
};
list($w1, $l1) = $order(57, 60);
list($w2, $l2) = $order(58, 59);

Upvotes: 1

Related Questions