1

I use in_array() to check whether a value exists in an array like below, But does not work as expected:

$projectId = $_GET['projectId'];
$userId = $_GET['userId'];

$qr2 = mysql_query("SELECT `userId`,`status` FROM `fndn_ProjectBacker` WHERE `projectId`='$projectId' && `status`='1'");

for($i = 1; $row2 = mysql_fetch_assoc($qr2); $i++) {
    $arr1[$i] = array($row2);
}

if (in_array($userId, $arr1)) {
    echo "True";
}

plz help me!

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Fatemeh Namkhah
  • 669
  • 1
  • 6
  • 22

1 Answers1

2

It doesn't work as you want it, because you create a two dimensional array with this:

$arr1[$i]=array($row2);
        //^^^^^^     ^ See here

Remove the array declaration here and you can also change out your for loop with a while loop, e.g.

while($row2 = mysql_fetch_assoc($qr2)){
    $arr1[] = $row2["userId"];
}

if (in_array($userId, $arr1)) {
    echo "True";
}

I also want to welcome you in 2015 and highly recommend to use mysqli_* prepared statements or PDO, they are much safer. (Also see: Why shouldn't I use mysql_* functions in PHP?)

Community
  • 1
  • 1
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • @FatemehNamkhah What does *not work* mean? Do you get any errors? Add error reporting to the top of your file(s): `` Also what is the output of: `print_r($arr1);` after the while loop? – Rizier123 Jul 26 '15 at 11:41
  • Array ( [0] => Array ( [userId] => 0 [status] => 1 ) [1] => Array ( [userId] => 5 [status] => 1 ) [2] => Array ( [userId] => 25 [status] => 1 )... – Fatemeh Namkhah Jul 26 '15 at 11:47
  • @FatemehNamkhah updated my answer. Just reload the page and try the code again. You just need to add the userid to your array. – Rizier123 Jul 26 '15 at 11:48