简体   繁体   中英

Use imploded result from MySql Query in PHP in_array() statement

Trying to use a string of coma separated values compiled from a mysql query within an in_array() statement. The problem is that the statement fails because the output of $array does not work in the in_array() function even though the pasted output of array does work...

$quiz = mysql_query("SELECT id FROM quiz WHERE quiz_page = '2'");
$array1=array();
while($quiz2 = mysql_fetch_assoc($quiz))
{
    $array1[]=$quiz2["id"];
}
$array = implode(",", $array1);
echo $array;
echo '<br>';

if (in_array(184, array($array))) {
echo '184 in $array';
} else {
echo '184 not in $array';
}
echo '<br>';

if (in_array(184, array(77,82,85,90,180,181,182,183,184,185))) {
echo '184 in array';
} else {
echo '184 not in array';
}

The result of the code above:

77,82,85,90,180,181,182,183,184,185
184 not in $array
184 in array

You need to be checking if (in_array(184, $array1)) {... instead. $array1 already contains each of numbers in a separate elements, like you have in your second if condition, eg

array(77,82,85,90,180,181,182,183,184,185)

When you do array($array) You get an array with one element , the entire imploded string, eg

array("77,82,85,90,180,181,182,183,184,185")

I'm not sure exactly what you're doing with this, but it looks like you might be able to eliminate the whole in_array problem by just including the 184 in your query

SELECT id FROM quiz WHERE quiz_page = '2' AND id = 184

And checking whether or not the query returns anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM