phparraysmultidimensional-arrayhtml-selectintersection

Print the unique column values from two 2d arrays as <option> tags and declare the "selected" attribute on intersecting values


I have two 2d arrays as seen below:

$users = [
    ['username' => 'Timothy'],
    ['username' => 'Frederic']
];
$users2 = [
    ['username' => 'Johnathon'],
    ['username' => 'Frederic'],
    ['username' => 'Peter']
];

I am trying to compare the contents of each array against each other in order to write html elements. I tried using a nested foreach as seen below:

foreach ($users as $user) {
    foreach ($users2 as $user2) {
        if ($user['username'] == $user2['username']) {
            echo "<option value=' " . $user['username'] . "' selected = 'selected'>" . $user['username'] . "</option>";
            break;
        } else {
            echo "<option value=' " . $user['username'] . "'>" . $user['username'] . "</option>";
        }
    }
}

My issue is that the items are being echoed more than once which is ruining my select element. Any ideas on how to compare the contents of each without printing duplicated options?

I want to achieve a list of each name eg:

-Timothy
-Frederic (this should be highlighted as it is in both arrays)
-Johnathon
- Peter

Solution

  • I would take it in a different way.

    //Create user array one
    $users = array();
    $users[] = array('username'=>'Timothy');
    $users[] = array('username'=>'Frederic');
    
    //create user array 2
    $users2 = array();
    $users2[] = array('username'=>'Johnathon');
    $users2[] = array('username'=>'Frederic');
    $users2[] = array('username'=>'Peter');
    
    $temp_array = array();
    
    foreach($users as $key => $value) {
        $temp_array[$value['username']] = '';
    }
    
    foreach($users2 as $key => $value) {
        $temp_array[$value['username']] = array_key_exists($value['username'], $temp_array) ? 'DUPLICATE' : null;
    }
    
    echo '<select>';
    foreach($temp_array as $key_value => $status) {
        echo "<option value='{$key_value}' ".(($status == 'DUPLICATE') ? 'selected style="background-color: yellow;"' : '').">{$key_value}</option>";
    }
    echo '</select>';
    

    I'll let the array take care of it self, if it shares the same key, it will merge, then just flag it with "duplicate".