Hanner Hanner - 1 month ago 10
PHP Question

How to get rid of undefined offset?

I am trying to remove undefined offset error from the following code but could not figure it how.

$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';


This code gives me correct answer but it outputs the following error:


E_NOTICE : type 8 -- Undefined offset: 1 -- at line 11


How do I change my code to remove the error. In a case like when $number=20.5, there is no error. Thanks.

Answer

This will work:

list($firstpart, $secondpart) = explode('.', $number.(strpos($number, '.') === false ? ".0" : ''));

And here is an explanation so I don't get accused of witchcraft :-)

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
    );