PHP未定义变量,然而脚本工作完美,如果我定义变量它不工作


PHP Undefined Variable, yet the script works perfect, if I define the variable it does not work

我有一个未定义变量的问题,如果我定义变量脚本不能正常工作,我知道这是一个简单的答案,我只是找不到它。

下面是我的代码:(我在每个循环中使用这个)

$weight= ($item['weight']*$item['quantity']);  
$totalweight = ($totalweight + $weight) 
echo $totalweight;

脚本工作完美,给我正确的答案,除了我得到一个未定义的变量错误在第2行$totalweight

我试图设置变量,但它会破坏计算。

你需要在循环之外初始化变量,这样它就不会在每次迭代中被覆盖:

$totalweight = 0;
foreach ($items as $item) {
    $weight= ($item['weight']*$item['quantity']);  
    $totalweight = ($totalweight + $weight) 
}
echo $totalweight;

如何设置变量?PHP之所以产生这个通知,是因为你要求它将$totalWeight$weight相加,而它不知道$totalWeight是什么。

要删除此通知,可以执行以下命令:

$totalWeight = 0;
$weight= ($item['weight']*$item['quantity']);  
$totalweight = ($totalweight + $weight);
echo $totalweight;

虽然最好把这一行改成:

$totalweight = $weight;

(当然,除非这段代码运行在循环或类似的环境中)。