joethemovie joethemovie - 6 months ago 10
HTML Question

Removing extra commas when echoing out imploded array after $_POST

I have an array with 100 or so items in it. I'm pulling from a huge checklist in a form. The items the user checks off are displayed on the next page after submission.

I have the items displaying, but there are several commas populating the page as well. No doubt from the variables that remained unfilled.

Here are a couple of code snippets to give you the general idea:

<!-- Front Underspoiler -->
<input type="checkbox" id="frontUnderspoiler" name="frontUnderspoiler" value="Front Underspoiler"> Front Underspoiler
<br>
<br>
<!-- Bumper Corner Moldings -->
<input type="checkbox" id="bumperCornerMoldings" name="bumperCornerMoldings" value="Bumper Corner Moldings"> Bumper Corner Moldings
<br>
<br>
<!-- Bumper Corner Molding-(2 PC) -->
<input type="checkbox" id="bumperCornerMoldingTwoPc" name="bumperCornerMoldingTwoPc" value="Bumper Corner Molding-(2 PC)"> Bumper Corner Molding-(2 PC)
<br>
<br>


This is how the form is structured for each item. When the form is submitted the user is redirected to the next page. Here's how my
$_POST
and array are set up:

// ACCESSORIES
$allWeatherFloorMats = trim($_POST["allWeatherFloorMats"]);
$oneTenPowerOutlet = trim($_POST["oneTenPowerOutlet"]);
$frontLicPlateBrack = trim($_POST["frontLicPlateBrack"]);
$ashTray = trim($_POST["ashTray"]);
$ashTrayMountingSleeve = trim($_POST["ashTrayMountingSleeve"]);
$cigaretteLighter = trim($_POST["cigaretteLighter"]);
$sideSillPlates = trim($_POST["sideSillPlates"]);


Bringing the the data in structured into an array:

$accessoriesArray = array(
'1' => $allWeatherFloorMats,
'2' => $oneTenPowerOutlet,
'3' => $frontLicPlateBrack,
'4' => $ashTray,
'5' => $ashTrayMountingSleeve,
'6' => $cigaretteLighter,
'7' => $sideSillPlates,
'8' => $frontSideSillPlate,
'9' => $strakeKit);


The last bit in the body of the page that echos the array with commas:

<?php echo implode(',',$accessoriesArray); ?>


Here's what I'm receiving:


Your Vehicle Includes ,,,,,,,,,,,,,,,,,,Rear Bumper Applique,,,Side Window Deflectors,,,,,,,,,,,,Bumper Bib,,,Sunshade,,Sport Grille Gunmetal Trim,,,,,,,,,,,,,Tweeter Kit,,,,,,Footwell Illumination Kit- Blue,,,Exterior Auto-Dimming for Blind Spot Detection,,,,,,,,Alloy Wheels,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,STI Carbon Fiber Trunk Trim,,,,.


Is there a way to remove the items in the array that are causing the commas to appear prior to me echoing out the result? Thanks for taking a the time to check this out. I'm relatively new to PHP. Any advice would be greatly appreciated.

Answer
<?php echo implode(',', array_filter($accessoriesArray)); ?>

When array_filter is called without a second argument, all entries of array equal to FALSE will be removed. (The empty string converts to FALSE.)

Comments