mardi 6 juin 2017

Tricky PHP Nested IF statements challenge?

This mind bender of a nested if statement had me stumped. See it below as well as my attempt at it.

function mystery($a, $b, $c) {
$result = null;
if (strlen(trim($a)) == 0) {
    $result = $c;
}
else {
    if (strtolower(trim($b)) == "n") {
        if (!is_numeric($a)) {
            $result = $c;
        }
        else {
            $result = trim($a);
        }
    }
    else {
        if (strtolower(trim($b)) == "d") {
            if (!isdate($a)) {
                $result = $c;
            }
            else {
                $result = trim($a);
            }
        }
        else {
            $result = $a;
        }
    }
}
return($result);
}

My answer was that it does the following:

If the year is NOT in the valid format, give the current date.

If the month is November AND the year is NOT in the valid format, give the current date.

If the month is November AND the year IS in the valid format, give the current year.

If the month is December AND the year is NOT in a valid format, give the current date.

If the month is December AND the year IS in the valid format, give the current year.

If the month is NOT December, give the current year.

They then ask you to optimize it. So this is what I gave them.

function mystery($a, $b, $c) {

//if checkdate(2000, 12, 31)); [Y M D]

if checkdate($a, $b, $c){

if ($b==11){

    $result = $a;
}

elseif ($b==12) {

    $result = $a;
}

elseif (!$b==12) {

    $result = $a;
}

else {

    $result = $c;

    return ($result);
}
}

} 

Was my attempt correct on:

a) What the code does?

b) How to optimize it?

c) If it was wrong on a) and/or b) above what was the correct answer?

Aucun commentaire:

Enregistrer un commentaire