Link to home
Start Free TrialLog in
Avatar of myyis
myyis

asked on

php operator

How can I make the below return false. Is there an alternative for the greater operator (>), like strict greater?

if ('2test'>0) echo 'true';  
else echo 'false';
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Comparison operators are documented on the PHP.net web site.  
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/types.comparisons.php

Because PHP is a loosely typed language, it can "type juggle" the data when making loose comparisons.
http://php.net/manual/en/language.types.type-juggling.php

There is a "less than" sign < that will give you a false indicator in the expression.
Avatar of Marco Gasi
'2test' is a string, so if you write

if ('2test'>0) echo 'true';  

Open in new window


Php will get the length of the string '2test' and it will see that is greater than 0 so the condition always will return true. Maybe you want to wrrite $2test without quotes?

In addition if have to write

if ('2test'>0) {
   echo 'true';  
} else {
  echo 'false'; 
}

Open in new window

Avatar of myyis
myyis

ASKER

If the first character is numeric than interprets as integer,
if not it is string. There should be something to avoid the "first character check".


 ('test'>0)  -->  returns  false
 (' 2test'>0)  -->  returns  true
 ('_2test'>0)  -->  returns  false
What logic are you trying to apply here? How do want your code to behave - asking if some text is greater than some number doesn't really make logical sense?

Are you wanting the comparison to work on string length, just the numbers from the string, the first number, the first character?
Avatar of myyis

ASKER

$var1=1;
$var2='1test';

if ($var1>0)  echo 'true';

I want to make the below return false using the ">0" criteria since it is a string.

if ($var2>0)  echo 'true'; else return 'false';
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There should be something to avoid the "first character check".
Ha!  There should be pink unicorns, too.  But this is just the way PHP works.  I cannot think of any computer-science application where it would make sense to compare a multi-byte string variable to an integer.  Programmers just don't do that sort of thing.  If we have a little "higher level" view of what you're trying to achieve we might be able to suggest a better way to make sense of it.

<?php // RAY_temp_myyis.php
error_reporting(E_ALL);

$var1=1;
$var2='1test';

if ($var1>0)  echo 'true';

// I want to make the below return false using the ">0" criteria since it is a string.

if ($var2>0)  echo 'false';

Open in new window