Andy19955
Andy19955

Reputation: 33

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";
}else{
    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?

Upvotes: 0

Views: 149

Answers (2)

Bhanu Pratap
Bhanu Pratap

Reputation: 1761

  • main concept behind comparing between two or more values, is to make sure all values in same data type for numeric values we can type cast string values into their respected types (i.e int,decimal or float etc...).

    • for when we use less than "<" or greater than ">" operators most of the time values (i.e indexes etc) are in integer data type. this is valid for all most common programming languages.

Upvotes: 0

David
David

Reputation: 218808

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)

or:

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.

Upvotes: 2

Related Questions