I have an If Statement that isnt loading the right image any help would be great

<?php
   if($formattedNum6 > $PeriodSalesTarget):{
      echo '<img src="images/TargetMetGreen.png" alt="" />';}
      elseif($formattedNum6 > $CummulativePeriodSalesTarget):{
         echo '<img src="images/TargetMet.png" alt="" />';}
         else:{
            echo '<img src="images/TargetNotMet.png" alt="" />';}
            endif;
?>

$formattedNum6 = 515,839
$PeriodSalesTarget = 1,366,000
$CummulativePeriodSalesTarget = 503,600

So it should show TargetMet.png but instead is showing TargetMetGreen.png

If i change the PeriodSalesTarget to 999,999 it works so looks like it isnt treating the values as numbers but i dont know how to fix

Dani AI

Generated

Most likely cause: the values being compared are formatted strings (commas/thousands separators) rather than raw numbers. PHP converts a numeric string only up to the first non-numeric character, so "515,839" becomes 515 and "1,366,000" becomes 1 when coerced — which makes 515 > 1 evaluate true and triggers the first branch. Confirm the actual types/values with a dump:

var_dump($formattedNum6, $PeriodSalesTarget, $CummulativePeriodSalesTarget);

Fix: strip formatting and convert to a numeric type before comparing. Two simple, reliable approaches:

$cleanA = (int) str_replace(',', '', $formattedNum6);
$cleanB = (int) str_replace(',', '', $PeriodSalesTarget);

or, for values that may include currency symbols or decimals:

$clean = (float) preg_replace('/[^\d.-]/', '', $stringWithFormatting);

Then do comparisons on $cleanA, $cleanB, etc. Using is_numeric() on the cleaned value is a good sanity check before comparison.

Notes and best practice: keep numeric data as numbers in the application logic and apply number_format() (or other formatting) only when rendering output. Avoid mixing the alternative if (...) : ... endif; syntax with braces — use one style consistently. was right to suggest casting, but the cast needs to come after removing thousands separators. ’s “Use brackets” comment is not applicable to the if syntax here. Also double-check the image files themselves if the issue persists (file contents vs expected filenames).

Recommended Answers

All 2 Replies

[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

From http://php.net/manual/en/types.comparisons.php

But the number is not large enough for that to happen. I don't know which version PHP so for now, test this by calling these ints by adding (int) to the values in line 2.
Read how at http://php.net/manual/en/language.types.integer.php

Lastly, be sure your png graphics are what you think they are. Check those again.

Use brackets [ ] and try

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.