-3

Seems super trivial, but can't find a solution to this specific case on SO

A function may return a value of 0 OR another number, which I then want to store in a variable $s to calculate stuff. But can't find a clean way of doing it.

So for example:

function f() {
    $v = "0";
    return $v;
}

if($s = f() !== false) {
    echo $s;
    // ^ I want 0, but the value above is 1 (since it's true)
}

I tried returning it as a string

return "0" instead of a digit, but it doesn't work.

If I do this it will not evaluate to true so nothing will happen

if($s = f()) {
   // returns nothing
}

But when I var_dump(f()), it does show string '0' (length=1)

So I can do

if(var_dump(f()) == 0)

OR

if(f() == 0)

But is there not a cleaner way to do it, so the function may return 0 or another number and I can just capture it in a variable?

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
Robert Sinclair
  • 4,550
  • 2
  • 44
  • 46
  • 3
    Did you want `if (($s = f()) !== false)` ? – hobbs Apr 18 '19 at 03:08
  • damn it.. thank you! Feel so dumb now. Can you post this as an answer, I ran into this a few times before and I think others will find this useful – Robert Sinclair Apr 18 '19 at 03:09
  • 1
    @RobertSinclair this is what almost all php developer feels :D – NullPoiиteя Apr 18 '19 at 03:15
  • amen brotha, i'll bookmark this. Have ran into this a few times when querying tables – Robert Sinclair Apr 18 '19 at 03:16
  • 1
    I don't think it's specific to PHP. I think all languages would do that due to operator precedence (comparison is higher than assignment usually). `bool b = 3 == 5;` would almost always never compare `b = 3` to `5` unless you specifically told it to with parenthesis. –  Apr 18 '19 at 03:23

3 Answers3

2

Add parentheses:

if (($s = f()) !== false) {

Otherwise you're computing the value f() !== false and assigning it to $s, instead of assigning f() to $s and then comparing to false.

hobbs
  • 223,387
  • 19
  • 210
  • 288
2

First

if($s = f() !== false) {
echo $s;
// ^ I want 0, but the value above is 1 (since it's true)
}

Whats happening here is return value of f() is strictly compared to false, that is, "0" is compared to false. They are not strictly equal, hence f() !== false returns true, which is stored in $s as 1.

Next,

if($s = f()) {
// returns nothing
}

This doesnt enter the if block because $s contains "0" and it is loosely equal to false.

Next

if(var_dump(f()) == 0) or if(f() == 0)

this works because it is loosely comparing "0" to 0 which is true. Hence it enters the block.

Remember, if condition does loose comparision or == and === does strict comparision. More about it here.

So, this should work in your case

if(($s = f()) !== 0)

if f() returns integers

Nirup Iyer
  • 1,215
  • 2
  • 14
  • 20
1

Try some parenthesis:

if(($s = f()) !== false) {

To force $s to equal f(), not f() !== false