Avatar

is there any way to shorten this?... im guessing id be pretty inconvenient if the select box had all fifty states... the thing is, i need it to end up as one variable, which in this case is $select_box

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php 

$options = $_GET['options'];
switch ($options)
	{
		case 'option1' :
			$option1_select = 'selected';
			break;
		case 'option2' :
			$option2_select = 'selected';
			break;
		case 'option3' :
			$option3_select = 'selected';
			break;
	}

	$select_box = '
	<select name="options" >
      <option value="option1" '.$option1_select.'>option 1</option>
     <option value="option2" '.$option2_select.'>option 2</option>
      <option value="option3" '.$option3_select.'>option 3</option>
    </select>';


echo $select_box;

Refactorings

No refactoring yet !

A1494c6f53c6774959936726353b566f

The Disintegrator

November 28, 2007, November 28, 2007 08:58, permalink

No rating. Login to rate!

This is the one I use

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	$proveedores = consulta("SELECT * FROM proveedores ORDER BY Nombre");
	while ($fila = mysql_fetch_assoc($proveedores))
		$proveedores_list[$fila['id']]= $fila['Nombre'];
	mysql_free_result($proveedores);

	$proveedores_select = "<select name=\"provID\" id=\"provID\">\n\r<option value=\"\"></option>\n\r";
	foreach ($proveedores_list as $key => $value)
	{
		if($art['provID']==$key)
			$proveedores_select .= "<option value=\"$key\" selected=\"selected\">$value</option>\n\r";
		else
			$proveedores_select .= "<option value=\"$key\">$value</option>\n\r";
	}
	$proveedores_select .= "</select>\n\r";
441c4f02db55ef2cbe96027af7012e01

techietim

November 28, 2007, November 28, 2007 10:51, permalink

No rating. Login to rate!

This should do it.

1
2
3
4
5
6
7
<?php
echo '<select name="options">';
foreach(array("option1", "option2", "option3") as $i){
    $select = ($_GET['options'] == $i) ? ' selected="selected"':'';
    echo '<option value="'.$i.'"'.$select.'>'.$i.'</option>';
}
echo '</select>';
D5dee399558f101cba4c221a57a00aa9

Daniel

June 28, 2008, June 28, 2008 04:08, permalink

No rating. Login to rate!

Not sure if you've figured it out by now... or maybe got it from somewhere else? But you can do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

$selectedState = $_GET["state"]; // (your $_GET should be santized)
$states = array(
	"AL" => "Alabama",
	"AK" => "Alaska",
	"AZ" => "Arizona",
	"AR" => "Arkansas",
	"CA" => "California",
	etc...
);

$stateSelect = '<select>';

foreach ($states as $key => $value) {
	$selected = ($key == $selectedState) ? ' selected="selected"' : ''; 
 	$stateSelect .= '<option value="' . $key . '"' . $selected . '>' . $value . '</option>';
}

$stateSelect .= '</select>';

echo $stateSelect;

?>

Your refactoring





Format Copy from initial code

or Cancel