Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return true php

Tags:

php

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

like image 562
TSR Avatar asked Oct 20 '18 10:10

TSR


2 Answers

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

$res = returnTrue([]);
like image 87
Rémi Bosgaerd Avatar answered Sep 26 '22 13:09

Rémi Bosgaerd


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

like image 23
Elementary Avatar answered Sep 26 '22 13:09

Elementary