I had test today about PHP. Really basic one, which probably won't give me A++ (10/10), because of strange question he asked, he asked us to translate:

$temp = 10;

if ($temp == 0) {
    echo "it's 0 Celsius";
}
elseif ($temp < 0) {
    echo "it's chill outside";
}
else {
    echo "it's not chill outside";
}

Now I sat on my chair reading question about 10 times to be sure I read it properly. I solved it using case "<0":, but I don't know if it's correct, probably not, I would never use it, first of all, I once sought this and people are screaming their head off saying do not do this! this isn't optimal!! and yet I'm here, finding solution.

Is:

switch (true) {
    case $temp < 0:
        echo "it's chill outside"; 

this the correct way to translate middle line of if-chain above? Would you grade it as "good" if you were teacher.

If you want to translate the above ifs into switch correct way as I see it would be:

switch($temp) {
    case 0: 
        echo "it's 0 Celsius"; 
        break;
    default:
        switch($temp > 0) {
            case true: 
                echo "it's not chill outside"; 
                break;
            default: 
                echo "it's chill outside";
        }
}

Another way of doing it would be:

switch(true) {
    case ($temp > 0) : echo "it's not chill outside"; break;
    case ($temp < 0) : echo "it's chill outside"; break;
    default: echo "it's 0 Celsius";
}

But in real situation you do not benefit much from this translation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.