开发者

Php array search not working

Hi really need help here is my function.

function isdAuthorTrue( $post_id ) { 


    $coauthors = get_post_meta( $post_id, "coAuthors" );

    print_r($coauthors);
    // print_r output Array ( [0] => 78 )

     $key = array_search( 78, $coauthors );
     $key = 0;
     if($key !== false) {

       return true;

     } else {

       开发者_Go百科  return false;
          }
}

then i am trying to do and if statement around it that isnt working.

$test = isdAuthorTrue( 102 );

echo $test;

if($test){

    echo "yes";

}else{

    echo "no";
}

i keep getting no what am i doing wrong???


You're getting "no" because array_search returns the key, in this case, 0. PHP evaluates that as false. Edit: didn't notice the strict comparison -- no it doesn't.

Also, you're explicitly setting $key to 0...


As @marc points out, you can just use in_array... and simplify the whole function down to one line:

function isdAuthorTrue($post_id,$authorid=78) { 
    return in_array($authorid,get_post_meta( $post_id, "coAuthors"));
}


Array serach returns the key of the needle that is 0 that is false. You should do.

if($test !== false){

    echo "yes";

}else{

    echo "no";
}


Why do you set $key = 0? $key is the index. So it is never FALSE. Why not use in_array($needle, $haystack)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜