0

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' ;
        }
?>

3 Answers 3

1

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' ;
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.