Andy19955 Andy19955 - 1 year ago 71
PHP Question

PHP if/else is not working as it should

I have the following code:

if($value1 >= $value2){
echo "Value 1 is greater or equal to value 2";
echo "Something else";

The variables $value1 and $value2 are having their values from a database. The problem is that whenever this code run, it always echo the "Something else". Even if value1 is greater than value2.

Both of the variables are numbers. When I echo them:

echo $value1 . " and " . $value2;

I have the following result:
1300 and 500

Does anyone know what is causing this problem?

Answer Source

I have the following result: 1300 and 500

Your values are string data, not numeric data. They're just strings which happen to contain numeric characters. And since the character '1' is "less than" the character '5', the string '1300' is "less than" the string '500'.

Convert your strings to integers. Something like:

if((int)$value1 >= (int)$value2)


if(intval($value1) >= intval($value2)){

You could also store the numeric versions in variables of their own for later use as well, maybe include some error checking for the possibility of non-numeric strings, etc. But ultimately don't assume a value is numeric just because it intuitively looks like a number. Data types are important.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download