Note that there are some explanatory texts on larger screens.

plurals
  1. POfinding common prefix of array of strings
    text
    copied!<p>I have an array like this:</p> <pre><code>$sports = array( 'Softball - Counties', 'Softball - Eastern', 'Softball - North Harbour', 'Softball - South', 'Softball - Western' ); </code></pre> <p>I would like to find the longest common prefix of the string. In this instance, it would be <code>'Softball - '</code></p> <p>I am thinking that I would follow this process</p> <pre><code>$i = 1; // loop to the length of the first string while ($i &lt; strlen($sports[0]) { // grab the left most part up to i in length $match = substr($sports[0], 0, $i); // loop through all the values in array, and compare if they match foreach ($sports as $sport) { if ($match != substr($sport, 0, $i) { // didn't match, return the part that did match return substr($sport, 0, $i-1); } } // foreach // increase string length $i++; } // while // if you got to here, then all of them must be identical </code></pre> <p>Questions</p> <ol> <li><p>Is there a built in function or much simpler way of doing this ?</p></li> <li><p>For my 5 line array that is probably fine, but if I were to do several thousand line arrays, there would be a lot of overhead, so I would have to be move calculated with my starting values of <code>$i</code>, eg <code>$i</code> = halfway of string, if it fails, then <code>$i/2</code> until it works, then increment <code>$i</code> by 1 until we succeed. So that we are doing the least number of comparisons to get a result.</p></li> </ol> <p>Is there a formula/algorithm out already out there for this kind of problem?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload