Home > database >  How to apply an if condition when the variable shows a numeric value equal to 0?
How to apply an if condition when the variable shows a numeric value equal to 0?

Time:07-30

I am calculating the discount of a purchased product based on its original price and discounted price. The math operation works and I get the results correctly.

Currently, when there is no discount 0.00 is displayed, so I would like to show custom text instead of the value 0, the end result could be "no discount applied" or something similar.

To do this I had thought about if and else conditions but I don't know how to apply them correctly, I'm relatively new with this. Below I leave my code explaining some things, I hope someone help me and clarify this, I appreciate any answer, thanks.

The variables: I am working with woocommerce but I think this is irrelevant as php is the crucial part. In any case, I have two variables that recover the original price of the product and the discounted price:

$regular_price = $product->get_regular_price(); //Get original price
$total_discounted = $item->get_total(); //Get discounted price

The calculation: Below is the line of php code that calculates the discount taking into consideration the two variables. When there is no discount the value 0 is displayed, when the discount is applied the correct result is shown. Note that I calculate both the sum of the discount and the percentage.

<?php echo ' <span >'. number_format( ($regular_price - $total_discounted),2 ) .'€ ('. number_format( (($regular_price - $total_discounted) / $regular_price*100),1 ) .'%)</span> '; ?>

Below I leave what I see with var_dump performed on the two variables. In reality the xx are numbers that indicate the original price of the product which is never zero.

<?php 
var_dump($regular_price); 
string(2) "xx" //Content - xx indicates the original price of the product

var_dump($total_discounted); 
string(2) "xx" //Content - xx indicates the original price of the product
?>

My doubt is, how do I apply in if conditions if both variables never return 0? The calculation obviously returns 0 as a result but the variables do not.

CodePudding user response:

Here is the solution to the problem. I created other variables to define the if condition like so:

$discount_sum  = number_format( ($regular_price - $total_discounted),2 );
$discount_percentage = number_format( (($regular_price - $total_discounted) / $regular_price*100),1 ); 
  if ($discount_sum == 0 and $discount_percentage == 0) { 
  echo '<span >Nessuno sconto applicato</span>';
} else {
  echo '<span >'. wp_kses_post($discount_sum) .'€ ('. wp_kses_post($discount_percentage) .'%)</span>';
                }
  • Related