Justin
Justin

Reputation: 45360

PHP Evaluate Variables Look For Best Fit

Assuming I have four values:

$right 
$down
$left
$up

And I want to choose the best out of the four. The values can either be false, 0, 1-9, or D.

False is the worst, 0 is second, 1-9 varies obviously 9 is best, and finally D is the best of all (stands of double).

What is best way to check this in PHP? I was thinking first check for D in all variables. If no D, then look for the highest number in all four, then look for 0, then finally look for false.

Thanks.

Upvotes: 1

Views: 68

Answers (3)

Christopher
Christopher

Reputation: 21

This should give you the answer you are looking for.

$test['up'] = false;
$test['down'] = 4;
$test['left'] = 'D';
$test['right'] = 0;

// for display only
print_r($test);

asort($test,SORT_STRING);

// for display only
print_r($test);

// Array key of the last value in array / best
echo array_pop(array_keys($test));

Upvotes: 0

jnrbsn
jnrbsn

Reputation: 2533

I'd convert it to an array first (you could use compact() for that, or just store in an array to begin with), and then you could use uasort() with a user-defined comparison function:

function myCompare($a, $b)
{
    // Convert false and D to -1 and 10, respectively.
    $a = ($a === false ? -1 : ($a == 'D' ? 10 : $a));
    $b = ($b === false ? -1 : ($b == 'D' ? 10 : $b));

    return ($b - $a);
}

$arr = compact('right', 'down', 'left', 'up');

uasort($arr, 'myCompare');

Or on PHP 5.3+, you could use a closure:

$arr = compact('right', 'down', 'left', 'up');

uasort($arr, function ($a, $b) {
    // Convert false and D to -1 and 10, respectively.
    $a = ($a === false ? -1 : ($a == 'D' ? 10 : $a));
    $b = ($b === false ? -1 : ($b == 'D' ? 10 : $b));

    return ($b - $a);
});

Upvotes: 0

deceze
deceze

Reputation: 522332

It seems to me that you're interested in the result of up, down, left or right in the end, so it'd make sense to keep those as values in an array paired with their "strength" values and simply sort them. Rough, untested draft:

$values = array(
    array('type' => 'right', 'value' => false),
    array('type' => 'down',  'value' => 3)
    ...
);

usort($values, function ($a, $b) {
    static $order = array(false, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'D');

    $a = array_search($a['value'], $order, true);
    $b = array_search($b['value'], $order, true);
    return $a - $b;
});

Upvotes: 2

Related Questions