Forum Moderators: coopster

Message Too Old, No Replies

Check box arrays

         

bunny

7:59 pm on Dec 4, 2007 (gmt 0)

10+ Year Member



Can anyone help me with printing the array(check box name) using PHP? Here is sample code.

<?php

$retval = '<form name="myform action="post">
<input type="checkbox" name="array1[]" value="elem1" checked >feed1</label><br/>';
$retval .= '<input type="checkbox" name="array1[]" value="elem2" checked >feed2</label><br/>';
$retval .= '<input type="checkbox" name="array2[]" value="elem3" checked >feed3</label><br/>';
$retval .= '<input type="checkbox" name="array3[]" value="elem4" checked >feed4</label></form>';

echo $_POST['array1[]'];
print_r($_POST['array1[]']);
//print_r($array2);
//print_r($array3);

?>

I am trying to print the arrays (array1, array2, and array3) and also how can i join those 3 array elements into 1array?

please help me

thanks

mooger35

8:44 pm on Dec 4, 2007 (gmt 0)

10+ Year Member



Not really sure how you want to show it but this will echo the check box values and will place them into a "joined" array.

<?php
$retval = '<FORM ACTION="" METHOD="POST">'."\r\n".'
<input type="checkbox" name="array1[]" value="elem1" checked >feed1</label><br/>'."\r\n";
$retval .= '<input type="checkbox" name="array1[]" value="elem2" checked >feed2</label><br/>'."\r\n";
$retval .= '<input type="checkbox" name="array2[]" value="elem3" checked >feed3</label><br/>'."\r\n";
$retval .= '<input type="checkbox" name="array3[]" value="elem4" checked >feed4</label><br/>'."\r\n".'<input type="submit" name="submit" value="submit"></form>'."\r\n";

echo $retval;

$joined= array(); //initialize array

for($i=1;$i<4;$i++){
$array = "array$i";
if(isset($_POST[$array])) {
foreach($_POST[$array] as $value){
echo $value."<br>\r\n"; // echo value
$joined[] = $value; // place value into joined array
}
}
}

echo "<p><b>Joined Array</b><br>\r\n";
foreach($joined as $value){
echo "$value<br>\r\n";
}
echo "</p>";
?>

d40sithui

8:49 pm on Dec 4, 2007 (gmt 0)

10+ Year Member



bunny,
1) all you need to do is to rename your checkboxes to the same name. ie, name them all "array1[]", instead of "array2[]", "array3[]". this is how you would get them in one array.

2) your action should point to the receiving script. not "POST". change the first line to
$retval = '<form name="myform" action="actionScript.php" method="POST">

[edit] damn mooger beat me to it!

mooger35

8:55 pm on Dec 4, 2007 (gmt 0)

10+ Year Member



Ya I was thinking that too... changing all the names to array1[] would certainly make things easier. :-)

I just figured you were using the different post arrays elsewhere in the script.