Home > Software engineering >  If value is empty or 0,0 echo something else in php
If value is empty or 0,0 echo something else in php

Time:12-03

i code a value for my progress bar in percent. But i need a if / else for the case, when supply is "null" and 0,0. Doesn't work so far. Maybe someone can help me out.. what is wrong here. I appreciate it.

case 'supplyper':
                    $x = $coin->available_supply;
                    $y = $coin->total_supply;

                $percent = $x/$y;
                $percent_friendly = number_format( $percent * 100, 0 ) . '%'; // change 2 to # of decimals

                if (empty($y)) {
                    $text = '0';
                }
                
                // Evaluates as true because $var is set
                if (isset($y)) {
                    $text = '' . $percent_friendly . '';
                }

CodePudding user response:

As it seems that $coin->total_supply is a string, first you need to make sure that it can be turn into a valid numeric value. It seems you are using the character ',' as your decimal separator so wee need to replace it with the '.' in order to make it a valid float. So lets try this:

$y = str_replace(',', '.', $coin->total_supply);

Now we need to make sure $y is a valid float representation:

$y = floatval($y);

Now check for $y not being zero(0) before you calculate the percentage otherwise you are open to a division by zero error.

You are very close, try this:

$x = str_replace(',', '.', $coin->available_supply);
$x = floatval($x);

$y = str_replace(',', '.', $coin->total_supply);
$y = floatval($y);

if (empty($y)) {
    $text = '100%';
} else {
    $percent = $x/$y;
    $percent_friendly = number_format( $percent * 100, 0 ) . '%'; // change 2 to # of decimals
    $text = '' . $percent_friendly . '';
}
  •  Tags:  
  • php
  • Related