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!

1 Answer 1

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?)

Sign up to request clarification or add additional context in comments.

3 Comments

@FatemehNamkhah What does not work mean? Do you get any errors? Add error reporting to the top of your file(s): <?php ini_set("display_errors", 1); error_reporting(E_ALL); ?> Also what is the output of: print_r($arr1); after the while loop?
Array ( [0] => Array ( [userId] => 0 [status] => 1 ) [1] => Array ( [userId] => 5 [status] => 1 ) [2] => Array ( [userId] => 25 [status] => 1 )...
@FatemehNamkhah updated my answer. Just reload the page and try the code again. You just need to add the userid to your array.

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.