alamizo alamizo - 2 months ago 5
PHP Question

How can I echo out content of if statement

i have 5 of these:

if(isset($_POST['checkbox'])) {
$name = "Alex";
}


How can I echo the name of every selected checkbox outside of the if statement?

Answer

From your example, build an array of $name:

if(isset($_POST['checkbox'])) {
   $name[] = "Alex";
}
if(isset($_POST['checkbox1'])) {
   $name[] = "Bob";
}

Then either:

echo implode(', ', $name);

Or:

foreach($name as $value) {
    echo $value;
}

But actually I'm wondering why not just set the values in the form inputs (use an array):

<input type="checkbox" name="checkbox[]" value="Alex">
<input type="checkbox" name="checkbox[]" value="Bob">

Then:

foreach($_POST['checkbox'] as $value) {
    echo $value;
}