...

View Full Version : Resolved Noob needs help with very small problem



IZZO
03-06-2009, 04:02 AM
Very new to php. I need to understand what I'm doing wrong here.
Warning: Invalid argument supplied for foreach() in /home/fpforum/public_html/php/send.php on line 5



$radio1 = $_POST['group1'];
$radio2 = $_POST['group2'];

foreach($_POST[checkbox] as $box) {
$box = $box + 0;
}

$total = $radio1 + $radio2 + $box;

Echo " <b>Total " . ($total) ." </b>";


When i was looking at a tutorial they showed the foreach argument being used pretty much the same way i am using it. What am i doing wrong?

rangana
03-06-2009, 04:13 AM
You might miss to add highlighted:


$_POST['checkbox']

IZZO
03-06-2009, 04:17 AM
I have tried it like that also. Still didn't work

kokjj87
03-06-2009, 04:22 AM
use:

$totalbox++;
instead of

$box = $box + 0;

orelse $box will reset on each loop



<?php
$radio1 = $_POST['group1'];
$radio2 = $_POST['group2'];

//make sure that it is an array
if(is_array($_POST['checkbox']))
{
$totalbox = 0;
foreach($_POST['checkbox'] as $box) {
$totalbox++;
}
}

$total = $radio1 + $radio2 + $totalbox;

Echo " <b>Total " . ($total) ." </b>";
?>



use checkbox[] for your checkbox name

And on your html form:

<form method="post">
<input type="checkbox" name="checkbox[]" value="value1"/>
<input type="checkbox" name="checkbox[]" value="value2"/>
<input type="submit"/>
</form>

IZZO
03-06-2009, 04:29 AM
Thank you!
It shows that error only when there isn't a checkbox checked off, But when at least one is checked it does the math just fine with out an error. How would i fix that?

kokjj87
03-06-2009, 04:35 AM
You need to make sure that it is set first...

Replace:

if(is_array($_POST['checkbox']))
With:

if(isset($_POST['checkbox']) && is_array($_POST['checkbox']))

IZZO
03-06-2009, 04:54 AM
Thank you! Everything is working great now.
I should have known about the if isset because i just saw something about it in the tutorial not to long ago.

I had to use $box = $box + 0; still tho because when i used $totalbox++; it counted how many of the checkmarks where selected instead of adding the values together.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum