Return true php

Viewed 227

A friend got this question during an interview:

What should be the value of x so that the following function returns true.

<?php
function returnTrue( $x ){
    $x[$x] = $x;
    return $x != true;
}
$res = returnTrue(YOUR_ANSWER);
var_dump($res);
?>

The answer should be 3 characters max

3 Answers

That was interesting, I gave this test a quick try and the answer is :

$res = returnTrue([]);

of course this

returntrue([]);

works but not completely fine as you would receive the message

Warning: Illegal offset type in ....

You must keep in my in mind that string type also allows arrayAccess style so

the right answer is

$res=returntrue('0');
var_dump($res)// print true

When you give as argument the string '0' this code $x[$x]=$x give again the same string '0' wich will not produce any warning and will absolutely return true as the string '0' will always be evaluated as false and false!=true return true

And also for the other post now deleted, I also managed to solve it.

function returnTrue( $x )
{
    if( !is_array( $x ) ) {
        return false;
    }
    foreach( $x as $x ) {
        $x[] = $x;
    }
    return $x;
}

var_dump(returnTrue([!0]));
Related