1

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 ?

1

2 Answers 2

2

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.

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

6 Comments

strpos would check every position in the haystack, though, whereas with substr it only checks one position. So substr will be faster. Personally I can't think of how to make it better than the code in the question.
@Kolink: That's why I'm saying, it might be worse, depending on the size of the strings. I don't know the implementation of strpos and substr so running strpos might still be faster than creating a new string. Which code performs better really depends on the data in this case.
My $haystack contains 20 rows maximum of 5 chars approx.
@mnml: And what is the size of the needle? But with such a small data set, I don't think you will see any difference in the performance.
@felix The needle will always be 2char long
|
1

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.

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.