简体   繁体   中英

How can I simplify this PHP script?

I'd like to add "selected" attribute to a combo box. This is my PHP:

if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }

if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }

if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }

if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }

I may have over hundreds of IF's.

I've tried this one, but It seems not working:

for($a=1; $a<=4; $a++){
    if($results['status'] == $a)
    { $ok = "selected"; }
    else
    { $ok = ""; }

}

I'd like to make it as simple as possible. maybe 1 or 2 line. Because I have many combo box that should be treated this way

Edit (My combo box):

<select>
<option value="1" <?php echo $ok1; ?>>A</option>
<option value="2" <?php echo $ok2; ?>>B</option>
<option value="3" <?php echo $ok3; ?>>C</option>
<option value="4" <?php echo $ok4; ?>>D</option>
</select>

You can do this way,

<?php

// status list array
$selectValues = array(1, 2, 3, 4);

echo '<select name="combo_name">';
foreach($selectValues  as $value){
    $selected = "";
    if($results['status'] == $value){
        $selected = ' selected="selected" ';
    }
    echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';  

?>

Since $results['status'] can only have 1 value, use dynamic variable names to make your life easy!

// initialize all 4 to blank
for($a=1; $a<=4; $a++){
    ${"ok" . $a} = "";
}
// set the one that is selected 
${"ok" . $results['status']} = "selected";

This answer is very scalable, you can just change the number on the "for" line from 4 to 1000 and it works with no extra code added.

All you have to do is make an array and loop through it-

<?php    
    $results_status = 3; // What ever your retrieve variable value is. In your case: `$results['status']`     
    $arr = array("1" => "A", 
                 "2" => "B", 
                 "3" => "C", 
                 "4" => "D"
                );
    ?>
    <select>
    <?php
    foreach($arr as $key => $val){
        $sel = ($results_status == $key) ? "selected='selected'" : "";
        ?>
        <option value="<?php echo $key?>" <?php echo $sel; ?>><?php echo $val?></option>
<?php }?>
</select>

You need to check every time for the selected value in the combo box.

Hope this helps

$combolength - the number of options in combo

$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
    case $results['status']:
        $ok[$results['status']]= 'selected';
        break;
} 

I personally think "simplify" what you already have is not the way to go about this. If you are not using a framework, I think you should instead ask how to make your script reusable , especially since you say "I have many combo box(es) that should be treated this way." Not using a contained element like a function/method sounds like a lot of extra work from a hardcoding standpoint. I personally would create a class that you can make form fields standardized and that you can feed an array into with dynamic key/value arrays. Simple example:

/core/classes/Form.php

class Form
    {
        # The idea here is that you would have many methods to build form fields

        # You can edit this as you please
        public function select($settings)
            {
                $class      =   (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
                $id         =   (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
                $selected   =   (!empty($settings['selected']))? $settings['selected']:false;
                $other      =   (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
                ob_start();
            ?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
    <?php foreach($settings['options'] as $key => $value) { ?>
    <option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
    <?php } ?>
</select>
            <?php
                $data = ob_get_contents();
                ob_end_clean();
                return $data;
            }
    }

To use:

# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
    'name'=>'status',
    'class'=>'classes here',
    'id'=>'select1',
    'other'=>array(
        'data-instructions=\'{"stuff":["things"]}\'',
        'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
    ),
    # Options can be assign database returned arrays
    'options'=>array(
        '_'=>'Select',
        1=>'A',
        2=>'B',
        3=>'C',
        4=>'D'
    ),
    'selected'=>((!empty($results['status']))? $results['status'] : '_')
    ));

Gives you:

<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
    <option value="_">Select</option>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM