How do I select an option in php from my array?

I am trying to select values โ€‹โ€‹from a given array. If the same value is returned in an array, then I need to select a parameter. How to do it?

Html

<select multiple="" class="Designers" style="width: 100px;">            
                          <option value="JOhn">JOhn</option>
                          <option value="JOhn1">JOhn1</option>
                          <option value="JOhn2">JOhn2</option>
                        </select>

      

PHP

 Array ( [0] => JOhn[1] => JOhn2);
$DesignerGet =  Array ( [0] => JOhn[1] => JOhn2[2] => JOhn2);
$DesinerEdit = explode(',',$DesignerGet);

<?php if('JOhn2' ==  'JOhn2'){ ?>
 <option value="JOhn1">JOhn1</option>
<?php } ?>

      

Expected Result

<select multiple="" class="Designers" style="width: 100px;">            
                          <option value="JOhn" selected>JOhn</option>
                          <option value="JOhn1">JOhn1</option>
                          <option value="JOhn2" selected>JOhn2</option>
                        </select>

      

+3


source to share


3 answers


Use array_unique () function before using array.

$DesinerEdit = array_unique($DesignerGet);

      



Removes duplicate values โ€‹โ€‹and you can use the array however you want.

Refer to php manual for this function

0


source


Try the following:



 $DesignerGet =  Array ( [0] => JOhn[1] => JOhn2[2] => JOhn2);
    foreach($DesinerEdit as $key=>$val)
    {
       $selected = ($val == 'JOhn1')?"selected ='selected' ":'';
       <option value="JOhn1" <?php echo $selected ?>>JOhn1</option> 

    }

      

0


source


Try this way ..

<?php
    $arra = Array ('JOhn','JOhn2'); 
    $option = Array ('JOhn','JOhn1','JOhn2');
?>

<select multiple class="Designers" style="width: 100px;">            
    <?php foreach($option as $key => $value){?>
        <option value="<?php echo $value;?>" <?php echo (in_array($value,$arra)) ? 'selected' : '';?>><?php echo $value;?></option>
    <?php }?>
</select>

      

Here I used a in_array

function to check the values, if the values โ€‹โ€‹are in the get array then it will be selected else not

0


source







All Articles