Interesting PHP quirk in If ElseIf statement

Exercise: https://www.codecademy.com/courses/learn-php/lessons/booleans-and-comparison-operators/exercises/else-if-statements

My code 1

function whatRelation($num) {
if ($num === 0) {return “not genetically related”;}
elseif ($num < 3) {return “third cousins”;}
elseif ($num < 6) {return “second cousins”;}
elseif ($num < 14) {return “first cousins”;}
elseif ($num < 35) {return “grandparent and grandchild, aunt/uncle and niece/nephew, or half siblings”;}
elseif ($num < 100) {return “parent and child or full siblings”;}
else {return “identical twins”;}
}

print whatRelation(‘hello’);

Output: third cousins

My code 2

function whatRelation($num) {
if ($num == 0) {return “not genetically related”;}
elseif ($num < 3) {return “third cousins”;}
elseif ($num < 6) {return “second cousins”;}
elseif ($num < 14) {return “first cousins”;}
elseif ($num < 35) {return “grandparent and grandchild, aunt/uncle and niece/nephew, or half siblings”;}
elseif ($num < 100) {return “parent and child or full siblings”;}
else {return “identical twins”;}
}

print whatRelation(‘hello’);

Output: not genetically related

Anyone can explain the difference in the output please.

Hi,
=== is a stricter comparison than ==
=== compares both the value and the datatype, whereas == just compares the value.

Secondly, when you compare a integer to a string as you are, it’s going to try and convert the string to a integer. When it can’t, as with ‘hello’, it defaults to a value of 0.

So your first code will fail the first test, as the datatypes aren’t the same (string and integer), but will pass the first elseif because that’s only checking the values (and 0 is less than 3).

In your second code, it’s only checking values not types. So when it evaluates ‘hello’ to 0, that matches the 0 in the condition.

Hope that helps.

2 Likes

Your explanation is brilliant, thank you.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.