1

I came across this question. What am I missing?

function ninja($x, $y, $z) 
{

     if ($y != $z && $x == $y && $x == $z) {
        return "Yes";   
      }

    return "No";    
}

For what values of $x, $y, $z will this function return "Yes" ?

1

4 Answers 4

3

Since == and != allow type juggling, various combinations of values will allow the function to return Yes. One version is

function ninja($x, $y, $z) {
    if ($y != $z && $x == $y && $x == $z) {
        return "Yes";
    }

    return "No";
}

echo ninja(0, 'a', 'b');

Since non numeric strings - when compared to and type juggled to an integer - have the value 0, the strange result is;

* $x == $y    (0 == 'a')
* $x == $z    (0 == 'b')
* $y != $z    ('a' != 'b') (both are strings, so no type juggling)

The documentation of comparison operators will give some more type juggling ideas, the short version is that there are probably more combinations, but they're not always obvious. Reading it gives good motivation to learn to use === and !== though :)

Sign up to request clarification or add additional context in comments.

Comments

0

According to Your logic:-

if ($y != $z && $x == $y && $x == $z) 

so here

1. $y != $z
2. $x == $y
3. $x == $z

if I consider point 2 and 3 then

i. $x == $y
ii. $x == $z this means $y == $z

But You have a condition $y != $z

So Your above if() condition will never be true. It always return false.

1 Comment

Mathematically, but not in PHP. ii. is not correct for PHP.
0

This will return true.

ninja(0, false, 'a');

One of the quirks of PHP.

Comments

0

if you take

$x=0;
$y='z'; #only alphabet character 
$z='x'; #only alphabet character

Because PHP is [loosely-typed] language you can always cast string to number by adding a zero to it. So you have to take $x value is always 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.