finding common prefix of array of strings

If you can sort your array, then there is a simple and very fast solution.

Simply compare the first item to the last one.

If the strings are sorted, any prefix common to all strings will be common to the sorted first and last strings.

sort($sport);

$s1 = $sport[0];               // First string
$s2 = $sport[count($sport)-1]; // Last string
$len = min(strlen($s1), strlen($s2));

// While we still have string to compare,
// if the indexed character is the same in both strings,
// increment the index. 
for ($i=0; $i<$len && $s1[$i]==$s2[$i]; $i++); 

$prefix = substr($s1, 0, $i);

Leave a Comment