Undefined offset

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
yoni101kessler
Forum Newbie
Posts: 1
Joined: Sun Sep 25, 2011 5:33 pm

Undefined offset

Post by yoni101kessler »

hello!
im trying to get multiple input from checkbox to an array in php, using the following code:
<form...>
<input type="checkbox" name="hobbie[]" value="1">
<input type="checkbox" name="hobbie[]" value="2">
.....

<?php
$hob=array();
$hob=$_POST["hobbie"];
$i=0;
while ($hob[$i])
{
echo $hob[$i];
$i++;
}
?>

im getting the correct values from the hob array, but im getting the: " NOTICE: Undefined offset: 5", where 5 is the length of the array..


why is that? what am i doing wrong???

thanks!!!
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Undefined offset

Post by Eric! »

I don't think while($hob[$i]) will work. Try while(isset($hob[$i]))
danwguy
Forum Contributor
Posts: 256
Joined: Wed Nov 17, 2010 1:09 pm
Location: San Diego, CA

Re: Undefined offset

Post by danwguy »

use this...

Code: Select all

for($i=0; $i < count($hob); $i++) {
echo $hob[$i];
}
That will fix your undefined offset, you are getting that because the array actually starts at 0 and goes to 4, not 5 so when it hits 5 it tries to echo $hob[5] which doesn't exist
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Undefined offset

Post by twinedev »

And, also while for a low count like a max of 5, you wouldn't see much of a difference, for good programming practice is is better to do the follow so that you are not repeating the call to the count function each iteration:

Code: Select all

$c = count($hob);
for($i=0; $i < $c; $i++) {
    echo $hob[$i];
}
However why not just do the following, which also verifies that $hob exists (if they don't choose any checkboxes, it won't, and the above code will complain when you go to assign $hob)

Code: Select all

if (isset($_POST['hobbie'])) {
    foreach($_POST['hobbie'] as $key=>$val) {
        echo $val;
    }
}
else {
    echo '(No Hobbies Selected)';
}
Post Reply