PHP除以零错误

时间:2015-06-29 14:45:36

标签: php

我做了一些关于PHP中零错误除法的研究。我发现他们中的大多数人都说要像我在下面的代码那样做一个if语句,但我仍然收到错误,有人能告诉我我的代码有什么问题吗?

<?php 

$result = array(
  'price' => 0,
  'special' => 80
 );

$product = array(
  'savings' => round((($result['price'] - $result['special'])/$result['price'])*100, 0)
 );

if ($result['price'] == 0) {
  echo $result['price'];
} else {
  echo "You will save " . $product['savings'] ."%"; 
}

?>

我试过了两次

If == 0 and if != 0  

因为我对PHP很新,所以if语句不是指产品的价格= 0而不是回显价格而不是回应特价吗?

我不允许移动$product数组。

2 个答案:

答案 0 :(得分:1)

您必须在if / else语句中移动该部门。

$result = array(
  'price' => 100,
  'special' => 80
);

if ($result['price'] == 0) {
   echo $result['price'];
} else {
   $product = array('savings' => round((($result['price'] - result['special'])/$result['price'])*100, 0)
);
   echo "You will save " . $product['savings'] ."%"; 
}

答案 1 :(得分:1)

这似乎更有意义,省钱:首先检查价格是否高于特价,如果是,请执行计算。

$product = array(
  'savings' => ($result['price'] > $result['special'] ? (round((($result['price'] - $result['special'])/$result['price'])*100, 0)) : 0)
 );
相关问题