which is best array_search or in_array?

前端 未结 7 1025
滥情空心
滥情空心 2020-12-23 20:17

I have a large while loop function, every time it gets loaded for check with current URL name. So I need to know which one is better to check the UR

相关标签:
7条回答
  • 2020-12-23 20:43

    Based on the documentation of in_array and array_search, I'd think that it mainly depends on what you want to do with the information: if you need the entry, use array_search, if you just want to check if the url exists in the array, in_array should be enough.

    0 讨论(0)
  • 2020-12-23 20:44

    It's up to your array-size. -If you have a small array(like < 500k 32bit-key), in_array and array_search give you same performance isset(array[needle]) make no sense because of flip()

    -By big arrays(like > 1m 32bit key) There are really big difference between in_array and isset(array[needle])

    0 讨论(0)
  • 2020-12-23 20:45
    array1=array("a"=>"one","b"=>"two"); 
    
    if(in_array("one",$array))
    {
      echo "array exit"; 
     }
     else
      {
         echo " array not exist"; 
      }
    
    echo "</br>";
    //example of array_search():
     $b1=array("a"=>"one","b"=>"two");
        echo array_search("one",$b1); 
    

    in_array return true and false value and array_search return key of the array

    0 讨论(0)
  • 2020-12-23 20:51

    If you're only goal is to check if an URL exists in the array I'd go for in_array. Altough the best way is having keys set so you can just search by array key. That way you save alot of looping.

    $searchword = "test";
    echo $array[$searchword];
    
    0 讨论(0)
  • 2020-12-23 20:54

    it's different function in_array - return true if find value array_search - return position if find value

    $a = array('a', 'b');
    var_dump(in_array('a', $a)); // return true
    var_dump(array_search('a', $a)); // return 0 
    if (array_search('a', $a)) - false
    
    0 讨论(0)
  • 2020-12-23 20:59

    If it's a large array and in a loop, neither is "best". Instead use array_flip() on your array, so urls become keys. And use isset() to check for the presence.

    0 讨论(0)
提交回复
热议问题