phparrayscodeignitercodeigniter-3difference

Disable items in dropdown which are previously selected using codeigniter


I have created a dropdown which contains Job Positions. I want to disable the dropdown item which user has previously applied. Here to reduce my code i have created options_selected static to get selected job profile lists. Here $job_positions contains all job profiles and $options_selected contains all the items which he previously selected from job_positions. Now he can't select these options again these should be disabled.

   $job_positions =array('0' => 'Select', '1' => 'IT Staff', '2' => 'Customer Care', '3' => 'Sales', '4' => 'Doctor');
        $options_selected =array('1' => 'IT Staff','2' => 'Doctor');
        $opt_array=array();
        // extract the job position
          for ($i=0; $i < count($job_positions); $i++) { 
            $disabled = '';
            // extract the options_selected and compare with the job position and if match overwrite the variable disabled
            for ($x=1; $x <= count($options_selected); $x++) { 
                if ($options_selected[$x]==$job_positions[$i]) {
                    $disabled = 'disabled';
                }
            }
            $opt_array[]= '<option '.$disabled.' value="'.$job_positions[$i].'">'.$job_positions[$i].'</option>';
          }
echo form_dropdown('category', $opt_array);

Solution

  • You can use the array_diff() function which compare the values of two arrays and returns the differences.

    $job_positions =array('0' => 'Select', '1' => 'IT Staff', '2' => 'Customer Care', '3' => 'Sales', '4' => 'Doctor');
    $options_selected =array('1' => 'IT Staff','2' => 'Doctor');
    
    $position = array_diff($job_positions,$options_selected);
    
    echo form_dropdown('category', $position);