Joncom
Joncom

Reputation: 2146

I'm not sure how to get around this notice

When I execute the following script:

<?php
$num = 3;
list($num, $dec) = explode(".", $num);
?>

PHP says:

Notice: Undefined offset: 1 in /home/www/test.php on line 3

Other than disabling these notices, is there a way I can prevent this notice from showing up?

Upvotes: 1

Views: 83

Answers (3)

Luca Rainone
Luca Rainone

Reputation: 16458

try this

$num = 3;

// forces to show the decimal point
$rnum = sprintf("%1\$.2f",$num);

list($num, $dec) = explode(".", $rnum);

EDIT for completeness:

alternatively you can also use number_format:

$rnum = number_format($num, 2); 

as suggested by Bojan Dević

Upvotes: 3

BugFinder
BugFinder

Reputation: 17858

While your code doesnt make actual sense, Im going to assume that you've done it as a quick way to produce an error.

If you added your first line of code to be

ini_set('display_errors','0');

this supresses the display of errors - however, you should only do this once your project is done and deployed at the end.. otherwise you then dont suffer from the "why is it an empty page" or "why did it not do.."

Upvotes: -1

Korvin Szanto
Korvin Szanto

Reputation: 4501

This notice is telling you that you only have a single array value, one way to solve this would be to use array_pad:

list($num, $dec) = array_pad(explode('.', $num),2,0);

Here's a working example.

Upvotes: 1

Related Questions