return of array_search() considered false condition

Asked

Viewed 107 times

2

In my code, in the login screen I search in the comic the number of blogs that belong to the same user and put the ID of these blogs in an array, then assign it to a session variable (I want my code to allow the user after logging in to access their blogs just changing the ID in the url). After the user is on your blog and changes the url, I use the session variable $blogs and compare it to the changed url ($url). The code below should check whether the array (with 2 positions), referring to the session variable, contains the url passed by the user. The problem is that PHP considers the array index 0 ( return of the array_search() function as a false condition, so it considers that the user has only 1 blog. I would like to know how to rewrite the code to avoid this problem:

if( isset($_GET['idBlog']) ){
    $url = $_GET['idBlog'];
    $blogs = $_SESSION['idBlog'];
    if( is_array($blogs) ){
        $index = array_search($url, $blogs);
        if( !is_nan($index) ){
            $blogAtual = $blogs[$index];
        } else {
            $msg = "<script> alert('O blog que você quer acesar não é seu') </script>";
    }
}

1 answer

2

If I understand correctly, just change the check:

if( is_array($blogs) ){

    if( ($index = array_search($url, $blogs)) !== false ){
            $blogAtual = $blogs[$index];
        } else {
            $msg = "<script> alert('O blog que você quer acesar não é seu') </script>";
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.