Page 1 of 1

Undefined offset

Posted: Sun Sep 25, 2011 5:48 pm
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!!!

Re: Undefined offset

Posted: Sun Sep 25, 2011 6:52 pm
by Eric!
I don't think while($hob[$i]) will work. Try while(isset($hob[$i]))

Re: Undefined offset

Posted: Sun Sep 25, 2011 9:06 pm
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

Re: Undefined offset

Posted: Sun Sep 25, 2011 11:24 pm
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)';
}