undefined index ??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dannyd
Forum Commoner
Posts: 56
Joined: Wed Jan 23, 2008 11:31 am

undefined index ??

Post by dannyd »

**** PLEASE USE THE CODE TAG *****

Code: Select all

<?PHP
 
$p1 = $_POST['p1'];
$p2 = $_POST['p2'];
$p3 = $_POST['p3'];
 
 
 
$total = $p1 + $p2 + $p3;
 
echo "Your Total is: " . $total;
 
 
 
?>

How come I get an Undefined Index error with this code ? What am i doing wrong ? How do you get this error ?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: undefined index ??

Post by Christopher »

Better would be:

Code: Select all

$p1 = isset($_POST['p1']) ? intval($_POST['p1']) : 0;
$p2 = isset($_POST['p2']) ? intval($_POST['p2']) : 0;
$p3 = isset($_POST['p3']) ? intval($_POST['p3']) : 0;
(#10850)
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: undefined index ??

Post by Ambush Commander »

Or even better

Code: Select all

 
function postInt($key) {
  if (!isset($_POST[$key])) return 0;
  return intval($_POST[$key]);
}
$p1 = postInt('p1');
$p2 = postInt('p2');
$p3 = postInt('p3');
 
Post Reply