0

I am trying to echo a specific message if the numerical value of $mqmtxt is greater than 20.

The value is in a txt file, the value is 7 so should be showing NO WARN but is showing WARN. Not sure what I am missing here.

<?php
   $mqmtxt = file_get_contents("./MQM/mqmcount.txt");
   $mqmtxt = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $mqmtxt);
   if ($mqmtxt >= "20"){
      $mqmwarning = "WARN";
   }else{
      $mqmwarning = "NO WARN";
   }
?>

<!DOCTYPE html>
<html>
    <body>
        <div id="dispmqmcount"><?php echo $mqmtxt; ?></div>
        <div id="warning"><?php echo $mqmwarning; ?></div>
    </body>
</html>
5
  • 3
    What is var_dump($mqmtxt);? Commented Feb 25, 2019 at 11:23
  • change this line if ($mqmtxt >= "20"){ to if ($mqmtxt >= intval("20")){ Commented Feb 25, 2019 at 11:26
  • You are making a string comparison, not a int comparison. Try casting Commented Feb 25, 2019 at 11:28
  • Do the typecasting on $mqmtxt. The code would be like this if ( (int)$mqmtxt >= 20) {....) Commented Feb 25, 2019 at 11:28
  • The answer below (and comment) both solved the issue, the dump was 7 as stated in the question. Thank you all Commented Feb 25, 2019 at 11:30

1 Answer 1

6

You are comparing the string "7" with the string "20" and since '7' > '2' your if test passes and WARN is displayed. You need to convert both values to integer to correctly compare e.g.

if ((int)$mqmtxt >= 20) {
Sign up to request clarification or add additional context in comments.

5 Comments

A variable is always implicitly converted to an integer during compare so your cast to int is unnecessary.
@emix Always?! Since you can use greater-than operators to compare strings too, that can't be true.
Not sure what you mean @deceze. You can compare strings, but before PHP does that, both sides are converted to int.
@emix You're saying both strings in 'foo' > 'bar' are converted to ints before comparison?!
You took my words too literally ;) Of course there's this type juggling magic involved.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.