Saswat
Saswat

Reputation: 12806

in_array doesn't seem to work on arrays

My php script:

$cont = array();
$slq_get_previous_country_list = "SELECT country FROM aw_countries_v2 WHERE id ='11120'";
$result_previous_country_list = mysql_query($slq_get_previous_country_list);
while($row = mysql_fetch_assoc($result_previous_country_list))
{
   $cont[] = $row['country'];
}

print_r($cont);                 
$not_data = array();    
$new_contry = array("Greece",
                    "Israel",
                    "Macedonia - The Frm Yugoslav Rep Of",
                    "Malta",
                    "India");


foreach($cont as $c)
{
  if(in_array($c, $new_contry)) 
    {
        echo $c."\n";
    }
    else
    {
        $not_data[] = $c;
    }   
}

print_r($not_data);

$cont array:

Array
(
    [0] =>  Belgium
    [1] =>  Cyprus
    [2] =>  Czech Republic
    [3] =>  Fiji
    [4] =>  Finland
    [5] =>  Greece
    [6] =>  Iceland
    [7] =>  Ireland
    [8] =>  Israel
    [9] =>  Macedonia - The Frm Yugoslav Rep Of
    [10] =>  Malaysia
    [11] =>  Malta
    [12] =>  Monaco
    [13] =>  Poland
    [14] =>  South Africa
    [15] => Austria
)

$not_data array:

Array
    (
        [0] =>  Belgium
        [1] =>  Cyprus
        [2] =>  Czech Republic
        [3] =>  Fiji
        [4] =>  Finland
        [5] =>  Iceland
        [6] =>  Ireland
        [7] =>  Malaysia
        [8] =>  Monaco
        [9] =>  Poland
        [10] =>  South Africa
        [11] => Austria
    )

The result:

array(
      [0] => austria
     );

What am I doing wrong?

Upvotes: 0

Views: 167

Answers (1)

Martin
Martin

Reputation: 22760

You have spaces in your strings, and the in_array function is space and case sensitive, so try adding this as a precursor:

while($row = mysql_fetch_assoc($result_previous_country_list))
{
   $cont[] = trim($row['country']);
}

You may also want to try strtolower to compare both array's string values without case worries.

Also, it is recommended to NOT use MySQL_ but to develop up to MySQLi or even PDO.

Upvotes: 2

Related Questions