-1

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.

Hanner
  • 371
  • 3
  • 9

2 Answers2

2

Since you use two arguments for list() it attempts to reference index [0] and [1] from the explode(), however there is only [0] because explode() returns only one array element when there is no .. Use this instead:

$parts = explode('.', $number);
echo $parts[0];
echo isset($parts[1]) ? number_format($parts[1] ,0) : '0';
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

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
    );
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77