2

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

$a = "171E-10314";
if($a == '0')
{
echo "here";
}
else
{
echo "there";   
}

4 Answers4

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 ===.

Audite Marlow
  • 1,034
  • 1
  • 7
  • 25
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

iosifv
  • 1,153
  • 1
  • 10
  • 26
0

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

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
Murat Cem YALIN
  • 317
  • 1
  • 6
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.

Dinesh Patra
  • 1,125
  • 12
  • 23