Stack One
Stack One

Reputation: 25

displaying array content followed by a string in PHP

Here is a concise of my code structure. What I need to do is print the values of the check boxes (only if those are checked by the user) along with a string attached as a message. In essence the message should be like 'Remove following? 10,20,30'

With my coding I get something like Delete following?Array ( [0] => 15 [1] => 35 )

can someone help me solve this. Many thanks. (Note: Not all the proper code is mentioned that should come under <html></html> and presented what is relevant for understanding (As I believe sufficient)

<?php
if(isset($_POST['submit']))
{
echo "Remove following?";
print_r ($_POST['del']);
}
?>

<html>
<form>
// inside html in a dynamically created table I have the following
<?php
echo "<td class='tbldecor1'><input type='checkbox' name='del[]' value='$cxVal'></td>";
echo "<td class='tbldecor2' style='text-align:center'>".trim($rec["firstrow"])."</td>";
<?
<div><input type="submit" name="deleterec" id="deleterec" value="Delete"></div>
</form>
</html>

EDIT : Also I'm thinking, if I'm to use a loop for printing how do I replace 1,2,3,4,5 values by check box values that a user picks? The loop I'm thinking would be as follows;

 <?php 
 $a = array(1, 2, 3, 4, 5); 
 foreach ($a as $b) 
 { 
 print $b . " "; 
 } 
 ?> 

Upvotes: 0

Views: 56

Answers (3)

jeromegamez
jeromegamez

Reputation: 3561

You can do it with the help of implode :

$vals = $_POST['del'];
echo "Remove following? " . implode( ", ", $vals );

UPDATE (after @Waleed Khan's warning about HTML injection):

// Make sure everything is a number (non-numeric will be replaced with boolean falses)
$vals = filter_var_array( $_POST['del'], FILTER_VALIDATE_INT ); 
// Remove all boolean falses
$vals = array_filter( $vals );
// String output
$valString = implode( ", ", $vals );
echo "Remove following? {$valString}";

Upvotes: 2

SomeKittens
SomeKittens

Reputation: 39522

You might want to look into implode().

Your entire for loop can be replaced by:

echo implode(" ", $a);

Upvotes: 0

grasingerm
grasingerm

Reputation: 1953

Instead of print_r, which prints out readable information about a variable, use the implode command:

echo "Delete following? " . implode(", ",$_POST['del']);

Upvotes: 0

Related Questions