Php foreach add comma

How to separate foreach with comma! But the trick is not to add comma if there is only one result?

<form method='post' id='userform' action=''> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxcat[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxcat[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxcat[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxcat'])) 
{
    foreach ($_POST['checkboxcat'] as $v) {

    
    print_r(implode(", ", $v));
}
}
?>

Hi letsforum,

You actually don’t need the foreach loop. Just pass the array to implode - it’ll only add a comma if there’s more than one element.

if (isset($_POST['checkboxcat'])) {
    $optionsString = implode(", ", $_POST['checkboxcat']);
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.