2

Why below code is printing the "here", it should be "there"

$a = "171E-10314";
if($a == '0')
{
echo "here";
}
else
{
echo "there";   
}
6
  • it's working as expected here.
    – Calimero
    Nov 26, 2015 at 16:19
  • according to the code, $a does not equal zero - it equals some strange string Nov 26, 2015 at 16:19
  • any reason why it 171E-10314 is equal to 0 so printing here Nov 26, 2015 at 16:21
  • @RamRaider the OPs issue is happening here - 3v4l.org/Iv1mi
    – Sean
    Nov 26, 2015 at 16:21
  • ok - that is kinda weird! Nov 26, 2015 at 16:24

4 Answers 4

5

PHP automatically parses anything that's a number or an integer inside a string to an integer. "171E-10314" is another way of telling PHP to calculate 171 * 10 ^ -10314, which equates to (almost) 0. So when you do $a == '0', the '0' will equate to 0 according to PHP, and it returns true.

If you want to compare strings, use the strcmp function or use the strict comparator ===.

0
1

when you use the == comparison, PHP tries to cast to different data types to check for a match like that

in your case:

  • '0' becomes 0
  • "171E-10314" is still mathematically almost 0 but I think PHP just rounds it to 0 due to the resolution of float.

check this link for a visual representation: http://www.wolframalpha.com/input/?i=171E-10314

0

As per the answers given I tried to convert the string into numerical:

$a = "171E-10314" + 0;
print $a;

And I got output as 0.

Thats why it is printing here.

0

Use === /*(this is for the 30 character)*/

2

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.