Jump to content

Problems with explode and implode - values partially being erased


sleepyw

Recommended Posts

I recently got help here on an issue regarding multiple selections from a form drop-down box. Everything seemed to work fine at first, but now I'm seeing a hiccup and don't understand what I'm doing wrong.

 

I have a multiple select HTML dropdown box with values that includes multiple words. Let's say, for example, the options in that box are Red, Blue, Light Blue, Dark Blue. When I submit the form, it implodes the values with this:

$color = implode(", ", $_POST['color']);

to string them together like this in the db "Red, Blue, Light Blue, Dark Blue". So far, so good.

 

Now, when a user goes in to edit that form again, I explode the array so that the colors previously selected will show up as separate items in the dropdown box, like this:

$color_exploded = explode(", ", $rows['color']);
if(is_array($color_exploded)) {
while (list ($key, $color_val) = each ($color_exploded)) {
echo "<option value=" . $color_val . " selected>" . $color . "</option>";
}
}

 

So far, so good.

 

Now here's where the problem occurs. If one of the colors selected has 2 words with a space between, like Light Blue, and the user resubmits the form without changing that value, the PHP cuts off everything after the first word and just displays "Light" as the value.

 

Where is my code screwed up or what do I need to add to make sure it keeps the entire value after the space?

I can see how that would work, but it's not preferable in this case. If there's no other workaround, I'll have to do that, but the problem is the db fields also get printed to a report that exports to Excel, and it might be weird or confusing to some people to see values like "Light_Blue" instead of "Light Blue," even though I can "fix" the way that shows on the web page. Essentially, I have 2 different values now (the way I make it look on the web page without the underscore, then the real value as stored in the db).

try

$color_exploded = explode(", ", $rows['color']);
if(is_array($color_exploded)) {
while (list ($key, $color_val) = each ($color_exploded)) {
echo "<option value='" . $color_val . "' selected>" . $color . "</option>"; //add some '
}
}

if(is_array($color_exploded)) {

 

is obsolete as explode only returns something different then an array when:

 

  Quote
If delimiter  is an empty string (""), explode() will return FALSE.

 

echo "<option value='" . $color_val . "' selected>" . $color . "</option>"; //add some '

 

I would replace that with:

 

echo '<option value="',$color_val,'"',(($color_val === $chosen_color)?' selected="selected"':''),'>',$color,'</option>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.