joethemovie joethemovie - 1 year ago 54
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
<!-- Bumper Corner Moldings -->
<input type="checkbox" id="bumperCornerMoldings" name="bumperCornerMoldings" value="Bumper Corner Moldings"> Bumper Corner Moldings
<!-- Bumper Corner Molding-(2 PC) -->
<input type="checkbox" id="bumperCornerMoldingTwoPc" name="bumperCornerMoldingTwoPc" value="Bumper Corner Molding-(2 PC)"> Bumper Corner Molding-(2 PC)

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
and array are set up:

$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 Source
<?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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download