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!!!
Undefined offset
Moderator: General Moderators
Re: Undefined offset
I don't think while($hob[$i]) will work. Try while(isset($hob[$i]))
Re: Undefined offset
use this...
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
Code: Select all
for($i=0; $i < count($hob); $i++) {
echo $hob[$i];
}
Re: Undefined offset
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:
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
$c = count($hob);
for($i=0; $i < $c; $i++) {
echo $hob[$i];
}Code: Select all
if (isset($_POST['hobbie'])) {
foreach($_POST['hobbie'] as $key=>$val) {
echo $val;
}
}
else {
echo '(No Hobbies Selected)';
}