0

I am using a class from somebody else and are getting an unexpected result. I already have an idea how to work around it, but I would like to understand why this happens.

class Pay {
  public function checkStatus {
    $check[0] = "000000 OK"
    return $check[0]
  }
}

$status = $cart->checkStatus ();
$payed = ( $status == "000000 OK" ? true : false);

The problem is that $status is somehow 1 when printing (could be also 'true' (have to check later at home)). Also payed is set to 'true' while I expect 'false' because of the wrong value of $status. Hope somebody can explain to me what is happening.

Matthieu
  • 437
  • 6
  • 16

2 Answers2

4

Try this:

$payed = ( $status === "000000 OK" ? true : false);

=== operator checks if $status and your string are equal and from the same type (string). More information you can find here: http://php.net/manual/en/language.operators.comparison.php

I tested it:

class Pay {
  public function checkStatus() {
    $check[0] = "000000 OK";
    return $check[0];
  }
}

$cart = new Pay();
$status = $cart->checkStatus();
echo $status; // returns "000000 OK"
$payed = ( $status == "000000 OK" ? true : false);
echo $payed; // returns 1
$payed = ( $status === "000000 OK" ? true : false);
echo $payed; // returns 1

If i echo $status it returns 000000 OK as string. I don't know whats your problem.

q0re
  • 1,401
  • 19
  • 32
  • That would then probably solve that $payed is not what I expect, but I still don't understand why $check[0] gets changed from a string to an int or boolean when it gets saved into $status – Matthieu Mar 09 '15 at 07:46
  • updated my answer.. i dont know whats your problem. `$status` variable returns the string `000000 OK` as expected. – q0re Mar 09 '15 at 08:00
3

This happens because of your numeric or boolean value in $status. This causes your bit $status == "000000 OK" to evaluate your string to a numeric value (which is 1), thus resulting in true.

Please see this questions accepted answer for further explaination:

Comparing String to Integer gives strange results

Community
  • 1
  • 1
kasoban
  • 2,107
  • 17
  • 24
  • I still don't understand why $check[0] gets changed from a string to an int or boolean when it gets saved into $status – Matthieu Mar 09 '15 at 07:51