Php 如何消除未定义的偏移量?
我试图从下面的代码中删除未定义的偏移量错误,但无法理解如何删除Php 如何消除未定义的偏移量?,php,arrays,Php,Arrays,我试图从下面的代码中删除未定义的偏移量错误,但无法理解如何删除 $number = 20; $pack = 10; $i = 0; while ($number % $pack == 0) { $number = $number / $pack; $i++; } list($firstpart,$secondpart)=explode('.', $number); echo $firstpart; echo '<br>'; echo isset($secondpar
$number = 20;
$pack = 10;
$i = 0;
while ($number % $pack == 0)
{
$number = $number / $pack;
$i++;
}
list($firstpart,$secondpart)=explode('.', $number);
echo $firstpart;
echo '<br>';
echo isset($secondpart)? number_format($secondpart,0):'0';
$number=20;
$pack=10;
$i=0;
而($number%$pack==0)
{
$number=$number/$pack;
$i++;
}
列表($firstpart,$secondpart)=分解('.',$number);
第一部分;
回声“
”;
echo isset($secondpart)?数字格式($secondpart,0):'0';
此代码给出了正确答案,但它输出以下错误:
E_注意:类型8——未定义的偏移量:1——在第11行
如何更改代码以删除错误。在类似$number=20.5的情况下,没有错误。谢谢。因为您使用了两个参数作为
list()
的参数,它试图从explode()
中引用索引[0]
和[1]
,但是只有[0]
,因为explode()
在没有时只返回一个数组元素。改用这个:
$parts = explode('.', $number);
echo $parts[0];
echo isset($parts[1]) ? number_format($parts[1] ,0) : '0';
这将有助于:
list($firstpart, $secondpart) = explode('.', $number.(strpos($number, '.') === false ? ".0" : ''));
这里有一个解释,这样我就不会被指控为巫术:-)
explode('.',$number)
设置为$firstpart
,但是第二部分是什么呢?有时$number可以有小数点。这就是为什么我还需要第二部分。@Zl3n如果除法的结果产生多个小数点怎么办?您提出的解决方案将失去这种精度。list($firstpart,$secondpart)=explode(“.”,$number.(strpos($number,”)==false?”.0:“)代码>请你可以发布你的答案和解释,因为它的工作,我想接受。
list($firstpart, $secondpart) =
explode(
'.', // explode on a period
$number.(strpos($number, '.') === false ? ".0" : '') // if the number does not contain a period then manually add ".0" so that explode can work but if it does then just leave it as-is
);