Nisto
Nisto

Reputation: 13

Foreach on checkboxes does not return values

I made a script before, that worked completely fine in PHP 5.2. But when recently going over to my friends server (version PHP 4.4.9), I noticed some actions didn't work the way they should. The outcome of what the checkboxes returned came out crazy...

This is the code I'm using: For the form:

<input type="checkbox" value="Box1" name="BoxGroup[]" />Box1
<input type="checkbox" value="Box2" name="BoxGroup[]" />Box2
<input type="checkbox" value="Box3" name="BoxGroup[]" />Box3

For the action script:

if($_POST['BoxGroup'] == true){ // If one of the checkboxes were checked...
    foreach($_POST['BoxGroup'] as $value){
    $BoxGroup .= ", ".$value; // Make the array into a string
    }
    $BoxGroup = substr($BoxGroup,2); // To skip ", " from the beginning of the $BoxGroup variable
}

Now, what this script does, is; when a user sends the form, it checks if one of the checkboxes were checked, and if so, it will make a string, like so: "value, value" etc. I insert these values to my database. When I preview what's been submitted to the database on a page, I get "ray / value / value", -- so only "ray" (as in "Array") was passed for the first box it seems.

Unfortunately, I can not update the server's version of PHP, since both the system operator and I, don't have the root password to it (I know it's crazy).

So what do I do?

Upvotes: 1

Views: 992

Answers (3)

Matthew
Matthew

Reputation: 48284

The other comments regarding implode are good advice, but I don't see how it fixes your problem. (Well, it actually could, if you initialize the variable to the return value of implode, but that doesn't fix the core issue here.)

Initialize $BoxGroup properly. I bet $BoxGroup = 'Array'; before the loop even runs... probably due to register_globals turned on. Eeeek, disable that.

In .htaccess:

php_flag register_globals off

To elaborate, I assume that if you did a var_dump($BoxGroup), you'd see that it already contains those values thanks to register_globals. The array gets treated as a string 'Array' when you concat it with another string.

Upvotes: 0

endo.anaconda
endo.anaconda

Reputation: 2468

I'd recommend the implode function: http://php.net/manual/en/function.implode.php

So your whole operation will getting a bit shorter and easier to overview. cheers

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

implode(', ', array_keys($_POST['BoxGroup']))

Upvotes: 1

Related Questions