panthro panthro - 6 months ago 52
PHP Question

Output a multi select with selected values from an array?

I have an array of jobs:

$jobs = ['j1', 'j2', 'j3', 'j4', 'j5'];

I also have an array of user jobs:

$userJobs = ['j1', 'j3'];

I'm outputting a multi select of all the jobs and I wish to have user jobs selected.

If a user only had one job i would do something like this:

foreach($jobs as $job){
echo '<option '.$job == $userJob ? 'selected' : ''.'>'.$job.'</option>';

But how to approach this comparing array without lots of loops?


Just flip the $userJobs array

$userJobs = array_flip(['j1', 'j3']);

then you can check with a simple isset($userJobs[$job]):

foreach($jobs as $job){
    echo '<option '.(isset($userJobs[$job]) ? 'selected' : '').'>'.$job.'</option>';