Jump to content

Recommended Posts

Hello. I'm having trouble wrapping my head around this issue and wonder if anybody could suggest a direction I could take.

 

I've got a function that grabs some preference data from a prefs table (a string that is exploded into an array). Once the string is exploded, I run it through a loop to output the options for an html select tag.

 

I would like to compare an existing field from another table with the items in the exploded array and if there's a match mark that option as "selected"

 

I currently have:

$package = $row['package'];

		$packages = explode(',',$prefs_pack);

		foreach($packages as $pack) {
			$packages .= '<option value="' . $pack . '">' . $pack . '</option>';
			}
		return $packages;	

 

The $package row comes from the other table fine. The question is where should I put the comparison and what method would you use? Should I throw a switch into the foreach loop? The $packages explosion produces 5 items in the array. So I need to compare $package (from the other table) to those 5 items and then stick "selected" for the item that matches into that option tag.

 

Any thoughts?

 

Thanks, in advance, I really appreciate the suggestions!

Link to comment
https://forums.phpfreaks.com/topic/265550-get-option-selected-into-foreach-loop/
Share on other sites

Here you go.  I also changed the name of your output var to avoid confusion with the $packages array that you're looping through.

$package = $row['package'];

		$packages = explode(',',$prefs_pack);
		$output = '';
		foreach($packages as $pack) {
			$output .= '<option value="' . $pack . '"' . ($pack == $package ? ' selected="selected"' : '') . '>' . $pack . '</option>';
			}
		return $output;	

 

Ahhhhhh yes! A ternary statement! They make my eyes water, face crunch up and I feel a sudden jerking of the shoulders whenever I (try not to but have to) think of them (a.k.a. crying)!

 

Thanks so much!

 

Edit: and it works beautifully. Thanks, again!

Cheers!

 

You don't need to use a ternary to do it, though: only required for single-line solution. 

 

You can do it in 3 lines with 1) concatenate first part 2) if... then... concat the "selected" bit, and 3) concatenate the last bit.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.