2

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 {

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

4 Answers 4

6

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...

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

2 Comments

Uh no, user is using === not == (with magic type conversion) 0!==false, 0==false
Not the case, he's using !== not != so types will be checked too. 0 == false will return true, 0 === false will not.
1

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"));
}

Comments

0

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";
}

Comments

0

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

Comments

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.