return from array_search () considered false condition

2

In my code, on the login screen, I search the BD for the number of blogs belonging to the same user, and put the ID of those blogs in an array, then assign it to a session variable (I want my code to allow the user later of logged in to access their blogs only by changing the id in the url). Once the user is on your blog and changes the url, I use the session variable $ blogs and compare it with the changed url ( $ url ).     The code below should check if the array (with 2 positions), referring to the session variable, contains the url passed by the user. The problem is that PHP considers the index 0 of the array (return of the array_search () function as a false condition, thus, it considers that the user only has 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>";
    }
}
    
asked by anonymous 06.04.2018 / 05:48

1 answer

2

If I get it right, you just need to 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>";
    }
}
    
06.04.2018 / 06:19