Search code examples
phpmysqlcodeigniter-2

Compare two arrays using foreach loop


In PHP I am going to edit some entity let say a project named: ABC this projects belongs to many countries while adding this project I used <select multiple="multiple"> and store all selected countries in a projectCountries table. Now when I start editing this project so I use same logic with a little change:

  1. populate all countries from countries table
  2. fetch all countries from projectCountries table which are associate with projectId

and I got two arrays:

Array ( 
    [0] => Array ( [countryId] => 1 [countryName] => Pakistan ) 
    [1] => Array ( [countryId] => 2 [countryName] => China ) 
) 

output from step-1

and

Array ( 
    [0] => Array ( [pcId] => 1 [countryId] => 1 [projectId] => 1 ) 
    [1] => Array ( [pcId] => 2 [countryId] => 2 [projectId] => 1 ) 
)

output from step-2

but I am confused how to show that country named China was already associated with the project (already selected in <select multiple="multiple">)

because to create <select multiple="multiple"> I used foreach loop. Now I could not guess how to compare two arrays in foreach loop so that I set selected="selected" in <option>.


Solution

  • Iterate over all countries and check if that country exists on the projectCountries output array.

    Something like this:

    $pc_list = array();
    foreach($project_countries as $pc) {
        $pc_list[] = $pc['countryId'];  
    }
    
    foreach($countries as &$country) {
        if(in_array($country['countryId'], $pc_list)) {
            $country['selected'] = TRUE;
        }
    }