Page 1 of 1

Undefined Index 2

Posted: Wed Jul 31, 2002 8:53 pm
by andrec
I saw another topic relating to this PHP error. The "solution" does not help me, however. I have a script below that keeps complaining about:
Notice: Undefined index: age ... in xxx.php on line 3. age is to be filled out in the form.

YES, the other value, e.g. E_ERROR, on error_reporting can suppress the error. However, as a newbie, I do want to keep it to E_ALL in order to understand more about the behaviour of PHP. My register_globals is On. Other environment info: Win2k/IIS/PHP 4.2.2. Can someone please kindly help me?

Code: Select all

<html><head><title>Age Comparison</title></head><body>
<?php
	$your_age=$_POST&#1111;'age'];
	if (is_null($your_age)) &#123;
?>
<form action="<?php echo $_SERVER&#1111;'PHP_SELF'] ?>" method="POST">
	Age:
	<input type="text" name="age" /> <br />
	<input type=submit name="age compare" />
</form>
<?php
&#125; else &#123;
	$age_diff=($age-16);
	if ($age_diff < 0) &#123;
		print ("You are younger than me");
	&#125;
	else &#123;
		print ("I am younger than you");
	&#125;
&#125;
?>
</body></html>


:(

Posted: Wed Jul 31, 2002 9:25 pm
by volka
most likely there is no post-data named 'age'
try

Code: Select all

print('<pre>');
print_r($_POST);
print('</pre>');
to examine the array.
If you're aware of this and only want to avoid the messages if no 'age' has been submitted try

Code: Select all

$your_age=(isset($_POST&#1111;'age']) ? $_POST&#1111;'age'] : '';
---
print_r
isset

Posted: Wed Jul 31, 2002 9:40 pm
by andrec
Thx A Lot, Volka,

I change yours to the following, then it works like a champ.

Code: Select all

$your_age=(isset($_POST&#1111;'age']) ? $_POST&#1111;'age'] : &#1111;b]NULL&#1111;/b]);
However, is this a standard way in PHP to determine whether a parameter has been supplied from a form page? I would love to hear how others do this. Thank You.

Posted: Thu Aug 01, 2002 1:30 am
by twigletmac
Using isset() is the best way of checking to see if a form variable was sent through because it tests to see if the variable is set :) .

Mac

Posted: Thu Aug 01, 2002 5:55 am
by volka
isset is nice :D
you could also use array_key_exists but why two mechanisms in only one script ;)

Posted: Thu Aug 01, 2002 7:23 am
by llimllib
Just for anyone else reading this, if you want to check that a key is set AND has a value, you can use empty()

Posted: Thu Aug 01, 2002 7:27 am
by twigletmac
When you use empty() remember that it's checking for strings that aren't set or have a value of 0 (zero) or an empty string.

Mac