Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is best array_search or in_array?

Tags:

arrays

php

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 URL name in large array within the while loop, in_array() or array_search() function.

like image 414
Thilak Avatar asked Dec 23 '10 11:12

Thilak


People also ask

Is in_array fast PHP?

PHP's in_array() function is really slow.

Is Array_search slow?

The array_search and in_array with $strict = true parameter are the slowest methods in our test.

Is in_array case sensitive?

The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

What is the use of in_array ()?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


2 Answers

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.

like image 190
mario Avatar answered Sep 19 '22 20:09

mario


There's no real answer here. So I tried it, myself.

$haystack = array (     'apple',     'banana',     'cherry',     'lemon',     'lime',     'orange',     'potato',     'rutabaga' ); $haySize = count($haystack);  $loops = isset( $_SERVER['argv'][1] ) ? $_SERVER['argv'][1] : 10000; // echo 'Loops: ' . $loops . "\n";  $start = microtime(true); for ($i = 0; $i < $loops; $i++) {     $needle = $haystack[ $i % $haySize ]; } $zeroTime = microtime(true) - $start; // echo sprintf('%0.3f', $zeroTime * 1000) . ' ms : zero time' . "\n";  $start = microtime(true); for ($i = 0; $i < $loops; $i++) {     $needle = $haystack[ $i % $haySize ];     $dummy = array_search($needle, $haystack); } echo sprintf('%0.3f', (microtime(true) - $start - $zeroTime) * 1000) . ' ms : array_search' . "\n";  $start = microtime(true); for ($i = 0; $i < $loops; $i++) {     $needle = $haystack[ $i % $haySize ];     $dummy = in_array($needle, $haystack); } echo sprintf('%0.3f', (microtime(true) - $start - $zeroTime) * 1000) . ' ms : in_array' . "\n";     echo sprintf('%0.3f', (microtime(true) - $start) * 1000).' ms : in_array'."\n"; 

For a typical use case, in_array wins, but the difference is negligible:

22.662 ms : array_search 22.104 ms : in_array 

Updated 2014-01-02: added noop loop to "zero the scale". Running PHP 5.4.17 on a new MacBook pro, this is a typical result:

24.462 ms : array_search 24.984 ms : in_array 
like image 34
Patrick Fisher Avatar answered Sep 22 '22 20:09

Patrick Fisher