Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP零除错误_Php - Fatal编程技术网

PHP零除错误

PHP零除错误,php,Php,我对PHP中的零除错误做了一些研究。我发现他们中的一些人说他们做了一个if语句,就像我在下面的代码中做的那样,但是我仍然得到了一个错误,有人能告诉我我的代码出了什么问题吗 <?php $result = array( 'price' => 0, 'special' => 80 ); $product = array( 'savings' => round((($result['price'] - $result['special'])/$result[

我对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'] ."%"; 
}

?>
由于我对PHP相当陌生,我的if语句是否意味着如果产品的价格=0,那么就呼出价格,如果不是,那么就呼出特殊价格


我不允许移动
$product
数组。

您必须在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'] ."%"; 
}

这似乎更有意义,在金钱方面:首先检查价格是否高于特价,如果高于特价,则进行计算

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

@johncode嘿,我编辑了我的代码,价格被设置为100,而不是0如果($result['price']==0)需要在该位之前进行检查:
/$result['price']
。分配
$product
时,您正在除以0,这似乎总是错误的,但不移动除法是否可行?无论您将除法放在何处,都必须检查以确保分母不等于零。另外-您的代码将一起覆盖产品。它没有添加额外的字段。是的,我知道我只是想看看如何避免这个错误。这正是我要找的!谢谢你是最好的
$product = array(
  'savings' => ($result['price'] > $result['special'] ? (round((($result['price'] - $result['special'])/$result['price'])*100, 0)) : 0)
 );