简体   繁体   中英

Determine if value exists in an associative array

Trying to determine if a value exists in an array like this:

$course_id = 1;

$sessions_query = $db->prepare("SELECT session_id FROM sessions WHERE course_id=:course_id");
$sessions_query ->bindValue(':course_id', $course_id, PDO::PARAM_INT);
$sessions_query ->execute();
$sessions = $sessions_query ->fetch(PDO::FETCH_ASSOC);

$session_id = 1;

if (in_array($session_id, $sessions['session_id'])) {
    echo "Valid session";
}
else {
    echo "Invalid session";
}

I know that the value 1 is in the sessions['session_id'] array because when I echo the array I can see that value. However, the function is still returning "invalid session". Is this not the correct way to use the in_array function?

->fetch() always returns one row, hence you'll have to loop through each session_id . You would do something like this:

Edited:efficient approach

Suppose your sessions table has 1000 entries and your $session_id matches with the 1st entry in the table. In this case the while() loop will not evaluate 1000 times, when a match is found, it'll break out from the loop.

$course_id = 1;

$sessions_query = $db->prepare("SELECT session_id FROM sessions WHERE course_id=:course_id");
$sessions_query ->bindValue(':course_id', $course_id, PDO::PARAM_INT);
$sessions_query ->execute();

$session_id = 1;

$session_value_exists = false;
while($sessions = $sessions_query->fetch(PDO::FETCH_ASSOC)){
    if ($session_id == $sessions['session_id'])) {
        $session_value_exists = true;
        break;    
    }
}
if($session_value_exists){
    echo "valid session";
}else{
    echo "invalid session";
}

As PDOStatement::fetch() returns a single row, you need to loop over your returned set to create an array first.

$course_id = 1;

$sessions_query = $db->prepare("SELECT session_id FROM sessions WHERE course_id=:course_id");
$sessions_query ->bindValue(':course_id', $course_id, PDO::PARAM_INT);
$sessions_query ->execute();
$sessions = array();
while($row = $sessions_query ->fetch(PDO::FETCH_ASSOC)){
    $sessions[] = $row['session_id'];
}

$session_id = 1;

if (in_array($session_id, $sessions)) {
    echo "Valid session";
}
else {
    echo "Invalid session";
}

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