Jump to content

help with array and implode


samoht

Recommended Posts

hello,

 

I have a form that stores checkbox values in an array named checkbox[].

 

on the confirmation page I am trying to list the array values that where selected.

 

When I used:

		$gcs = array($_POST['checkbox']);
		foreach ($gcs as $gc){
				echo '<tr><td> Gift card .............</td><td>$'.$gc.'.00</td></tr>'."\n";

		}	

the output was:

Gift card ............$Array.00

 

So I changed it to use implode like this:

		$gcs = array(implode(',', $_POST['checkbox']));
		foreach ($gcs as $gc){
				echo '<tr><td> Gift card .............</td><td>$'.$gc.'.00</td></tr>'."\n";

		}	

 

I get:

 

Gift card ..............$50,125,275.00

(assuming I chose 50 125 and 275 as values the first time through)

 

Why don't I get them separated??

 

my output should be:

Gift card ..............$50.00

Gift card ..............$125.00

Gift card ..............$275.00

 

Thanks for any help

 

 

Link to comment
https://forums.phpfreaks.com/topic/113636-help-with-array-and-implode/
Share on other sites

<?php
// Your first attempt
$gcs = array($_POST['checkbox']);

// If $_POST['checkbox'] is already an array, then you do not
// need to modify it before using your foreach.  Just use it
// as-is.
foreach( $_POST['checkbox'] as $gc ) {
  // Do something with $gc
}
?>

 

<?php
// Your second attempt
$gcs = array(implode(',', $_POST['checkbox']));

// Implode *returns a string*.  With the above line you have
// turned $gcs into a string and you *can not* use it in a
// foreach.  If you want to get a comma-delimited list of
// the elements in an array:
echo "These were selected: " . implode( ', ', $_POST['checkbox'] );
?>

On the confirm page, you can create a hidden input whose value is a delimited list of the selected values.  Use a delimiter that does not exist in one of the values.

 

<!-- on the confirm page -->
<input type="hidden" name="selected" value="1,2,4,7,11" />

 

<?php
// Processing page
$selected = explode( ',', $_POST['selected'] );
echo '<pre style="text-align: left;">' . print_r( $selected, true ) . '</pre>';
?>

This works fine:

<?php
if (isset($_POST['submit'])) {
if (isset($_POST['checkbox']))
	foreach($_POST['checkbox'] as $val)
		echo 'Gift card ............ $' . $val . '<br>';
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
<head>
<title></title>
</head>

<body>
<form action="" method="post">
<?php
for ($i=25;$i<225;$i += 25)
	echo '<input type="checkbox" name="checkbox[]" value="'. $i . '">$' . $i . '<br>';
?>
<input type="submit" name="submit" value="Test it!">
</form>


</body>
</html>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.