Undefined Index on Radio Buttons

I’m getting an error that I don’t understand…

At the bottom of my script I have a form with radio buttons like this…


// Display Friend-Requests.
echo "<li>
		<a href='/account/profile.php?user=$username&tab=about-me'>
			$username<br />
			<img src='/uploads/" . $photoName . "' width='80' alt='Thumbnail of ' . $username />
		</a>
		<fieldset id='friendRequestDecision'>
			<input id='" . $requestorID . "_1' name='friendRequestDecision[" . $requestorID . "]' type='radio' value='0' />
			<label for='" . $requestorID . "_1'>Decide Later</label>

			<input id='" . $requestorID . "_2' name='friendRequestDecision[" . $requestorID . "]' type='radio' value='1' />
			<label for='" . $requestorID . "_2'>Accept</label>

			<input id='" . $requestorID . "_3' name='friendRequestDecision[" . $requestorID . "]' type='radio' value='2' />
			<label for='" . $requestorID . "_3'>Decline</label>
		</fieldset>
	</li>\
";

And at the top of my script I have PHP to handle the form like this…


	if ($_SERVER['REQUEST_METHOD']=='POST'){
		// Form was Submitted (Post).

		// Initialize Errors Array.
		$errors = array();


		// **********************
		// Validate Form Data.	*
		// **********************
		foreach($_POST['friendRequestDecision'] as $requestorID => $decision){
			// Cast to Integers.
			$requestorID = (int)$requestorID;
			$decision = (int)$decision;

If I submit the Form with nothing selected, I get this error…

Notice: Undefined index: friendRequestDecision in /Users/user1/Documents/DEV/++htdocs/06_Debbie/account/manage_requests.php on line 56
Call Stack
#	Time	Memory	Function	Location
1	0.0013	95340	{main}( )	../manage_requests.php:0

I supposed since I don’t have this in my Form…

checked = 'checked'

…that could be causing this problem?

But what I don’t get is that I have a similar Form with TextAreas, and if I submit that Form with “Null” values it does NOT cause this same error (If Nulls are the issue, then I’d expect similar issues…)

What is going on?

And how can I fix my code so this error doesn’t happen?? :-/

Thanks,

Debbie

Radios and checkboxes are different from text input. If not checked, they aren’t in the input. So you’ll want to check isset() first.

QMonkey is correct, when working with an array of checkboxes for example you always need to ensure that the variable index exists in the $_POST super global. As well as that i would also recommend you use either the count() or sizeof() function as sometimes even if an array is set it can still be empty, see the below example.

if (isset($_POST['friendRequestDecision']) && sizeof($_POST['friendRequestDecision'])) {
    // Run your foreach code here
}