Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Unexpected bheaviour of in_array in PHP

    • 0
    • 1
    • 1
    • 2
    • 1
    • 0
    • 0
    • 0
    • 244
    Comment on it

    We have an associative array where its values are all Boolean and if we search for a string, we got true.

    Lets see an example.

    <?php
    $array = array(
      'count' => 1,
      'references' => 0,
      'ghosts' => 1
    );
    var&#95;dump(in&#95;array('aurelio', $array));
    

    And what we get is

    true
    

    Once again the in_array() function returns true. How is this possible?

    The in_array has certain parameters such as:

    0
    false
    
    0
    NULL
    array()
    

    To solve this problem you can use in_array's third parameter. So, if we write:

    <?php
    $array = array(
      'count' => 1,
      'references' => 0,
      'ghosts' => 1
    );
    var&#95;dump(in&#95;array('aurelio', $array, true));
    

    well finally get

    • false

      as we expect!

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: