Nasser Kamal
Nasser Kamal

Reputation: 113

check if value exist in database array not working

need to check if the value exist in array , the array created from database table, it just not working with me keep getting error says "in_array() expects parameter 2 to be array, string given" can someone please help ?

PHP code

<?php 
    $lang='en';
    $query_rsLanguages = "SELECT * FROM languages";
    $rsLanguages = mysql_query($query_rsLanguages);
    $languages_array = array();
    while($row = mysql_fetch_array($rsLanguages)){ 
      $languages_array[] = "\"".$row['language_sign']."\""; 
    }
    $languages_string = implode(",", $languages_array);
    if (in_array($lang, $languages_string)) {
        echo 'found' ;
        }
?>

Upvotes: 0

Views: 1917

Answers (3)

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

The above error is saying that the second parameter of the in_array should be an array, by using implode you are making it a string use the code below.

<?php 
    $lang='en';
    $query_rsLanguages = "SELECT * FROM languages";
    $rsLanguages = mysql_query($query_rsLanguages);
    $languages_array = array();
    while($row = mysql_fetch_array($rsLanguages)){ 
      $languages_array[] = $row['language_sign'];
    }

    if (in_array($lang, $languages_array)) {
        echo 'found' ;
    }
?>

Hope this helps you

Upvotes: 1

user4275254
user4275254

Reputation:

This will check if the String $lang exists inside your $languages_array or not

if (in_array($lang, $languages_array)) {
        echo 'found' ;
}

Upvotes: 1

Rhumborl
Rhumborl

Reputation: 16609

You are imploding $languages_array to a string and passing that to in_array, which is incorrect and unnecessary. As the error says you need to pass an array to search in. You just need to build the array of languages from your result and check that:

<?php 
    $lang='en';
    $query_rsLanguages = "SELECT * FROM languages";
    $rsLanguages = mysql_query($query_rsLanguages);
    $languages_array = array();
    while($row = mysql_fetch_array($rsLanguages)){ 
      $languages_array[] = $row['language_sign'];
    }

    if (in_array($lang, $languages_array)) {
        echo 'found' ;
    }
?>

Upvotes: 1

Related Questions