Reputation: 22041
I have made a function to search an array and lookup for values starting by the 2d param :
public static function arrayContainsValueStartingBy($haystack, $needle) {
$len = strlen($needle);
foreach ($haystack as $hay) {
if (substr($hay, 0, $len) == $needle) {
return true;
}
}
return false;
}
I feel like its not as optimized as it can be, could you give me some directions to improve it ?
Upvotes: 1
Views: 1067
Reputation: 212412
Not sure if the looping would be faster using array_filter:
$testArray = array('Hello',
'World',
'Aardvark',
'Armadillo',
'Honey Badger'
);
$needle = 'A';
class beginsWith {
private $_needle = NULL;
function __construct($needle) {
$this->_needle = $needle;
}
public function filter($string) {
return (strpos($string, $this->_needle) === 0);
}
}
$matches = array_filter($testArray, array(new beginsWith($needle), 'filter'));
var_dump($matches);
Though instantiating the beginsWith class probably adds overhead.
Upvotes: 1
Reputation: 816482
You have to profile the code to see whether it makes any difference (it could actually be worse, depending on the size of the strings you have), but you could use strpos
[docs] instead of substr
:
public static function arrayContainsValueStartingBy($haystack, $needle) {
foreach ($haystack as $hay) {
if (strpos($hay, $needle) === 0) {
return true;
}
}
return false;
}
Other than that I don't see much room for improvement. You have to iterate over the elements in any case, stopping as early as possible and you are already doing this.
Upvotes: 2