PHP未定义变量,但脚本工作完美,如果我定义它不起作用的变量
问题描述:
我有一个未定义的变量的问题,如果我定义的变量脚本不能正常工作,我知道这是一个简单的答案我就是找不到它。PHP未定义变量,但脚本工作完美,如果我定义它不起作用的变量
这里是我的代码:(我用这个在每个循环)
$weight= ($item['weight']*$item['quantity']);
$totalweight = ($totalweight + $weight)
echo $totalweight;
该脚本可以完美运行,并给了我正确的answerexcept我得到的线未定义的变量错误2 $总权重
我试图设置变量,然后打破计算。
答
需要初始化变量外循环所以它不是在每个迭代上覆盖:
$totalweight = 0;
foreach ($items as $item) {
$weight= ($item['weight']*$item['quantity']);
$totalweight = ($totalweight + $weight)
}
echo $totalweight;
+0
你撞上了头,我试图definfe循环内的变量 – HarryH 2013-03-07 02:26:34
答
你是如何设置变量的? PHP正在生成此通知,因为您要求它添加$totalWeight
和$weight
,并且它不知道$totalWeight
是什么。
去除这个通知,你可以这样做:
$totalWeight = 0;
$weight= ($item['weight']*$item['quantity']);
$totalweight = ($totalweight + $weight);
echo $totalweight;
虽然这可能只是最好改线路为:
$totalweight = $weight;
(当然,除非这个代码在一个循环或运行喜欢)。
该代码是没有意义的。如果你知道'$ totalweight'不存在为什么你有'($ totalweight + $ weight)'??? – 2013-03-07 02:15:30
如果变量未分配,第二行的要点是什么? – Tchoupi 2013-03-07 02:16:06
如果$ totalweight没有定义,你认为如何做$ totalweight =($ totalweight + $ weight)? – kennypu 2013-03-07 02:19:23