JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

PHP finds the common prefix of multiple strings [Case]

Author:JIYIK Last Updated:2025/03/19 Views:

This article shares with you the application of a small algorithm - finding the common prefix of a string array:

array(
   'abcdefg',
   'abcdfio',
   'abcdqle'
)

In the above array string, the common prefix is ​​'abcd'.

The first thing that comes to mind is to start from the first character of the first string and compare it with the characters of other strings in turn. If they are all equal, we save them until one is not equal, then we end the subsequent comparison.

The code is as follows

function commonPrefix($arr){
    $count = strlen($arr[0]);
    $prefix = '';
    for($i=0;$i<$count;$i++){
        $char = $arr[0][$i];
        $flag = true;
        foreach($arr as $val){
            if($char != $val[$i]){
                $flag = false;
                break;
            }
        }
        if(!$flag) break;
        $prefix .= $char;
    }
    return $prefix;
}

This code works great for finding the common prefix of the above array of strings.

But there is a serious bug in the above program. When the length of some strings in the array is smaller than the length of the first string, an error may occur. Let's look at the following array:

array(
  'abcde',
  'abc',
  'abcrhgh',
  'abcdfg',
  'abcfg'
);

We can see from the array above that the common prefix is ​​abc. During the comparison process, when comparing the fourth character d, we check whether the second string has only three characters. Therefore, $arr[1][3] does not have this variable. Therefore, an error is reported.

There are two solutions to this situation

Method 1: Before each comparison, determine whether the variable exists. If it does not exist, terminate the subsequent comparison directly.

Some of the code is as follows:

foreach($arr as $val){
   if(!isset($val[$i]){
            $flag = false;
            break;
   }
   if($char != $val[$i]){
       $flag = false;
       break;
   }
}

Method 2: Before searching and comparing, find out the length of the shortest string in the array and use this length as the termination condition of the loop.

The code is as follows:

function commonPrefix($arr){
         $count = strlen($arr[0]);
for($i = 0;$i<count($arr);$i++){
    if(strlen($arr[$i]) <= $count){
        $count = strlen($arr[$i]);
    }
}
    $prefix = '';
    for($i=0;$i<$count;$i++){
        $char = $arr[0][$i];
        $flag = true;
        foreach($arr as $val){
            if($char != $val[$i]){
                $flag = false;
                break;
            }
        }
        if(!$flag) break;
        $prefix .= $char;
    }
    return $prefix;
}

The above is the code for finding common prefixes in a string array. I hope it will be helpful to you.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Using CASE in PostgreSQL

Publish Date:2025/04/11 Views:124 Category:PostgreSQL

This article shows how to use the statement in PostgreSQL CASE . CASE How to use the statement in PostgreSQL case Statements are similar to those in general-purpose programming languages if-else . But in SQL, if you want to write IF-ELSE ,

Linux application - find files to copy [case]

Publish Date:2025/04/08 Views:66 Category:OPERATING SYSTEM

This article shares a Linux application case with you. The requirements are as follows: /a Contents under the directory /a/login1.txt /a/login2.txt /a/login3.txt /a/login4.txt /a/b/login5.txt /a/b/login6.txt We find all the file names start

Learning the Sorting Algorithm - Insertion Sort (Concepts)

Publish Date:2025/03/19 Views:96 Category:ALGORITHM

What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a

Learning path of sorting algorithm - direct insertion sort

Publish Date:2025/03/19 Views:176 Category:ALGORITHM

This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide

Learning the sorting algorithm - Binary Insertion Sort

Publish Date:2025/03/19 Views:143 Category:ALGORITHM

This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort Binary Insertion Sort Algorithm Steps Treat the first element of the first sequence to be s

The road to learning sorting algorithms - table insertion sort

Publish Date:2025/03/19 Views:194 Category:ALGORITHM

Table insertion sort was briefly mentioned in Insertion sort (concept) . I briefly summarized it and wrote this article. You can refer to it if you need it. Table insertion sort, as the name implies, uses an index table to sort the original

The road to learning sorting algorithms - Hill sort

Publish Date:2025/03/19 Views:52 Category:ALGORITHM

Hill sort is named after the designer of the algorithm, Hill. It is an improvement of Hill on the basis of insertion sort and can be said to be a special insertion sort. Here are the properties of insertion sort: First of all, the insertion

The road to learning sorting algorithms - merge sort

Publish Date:2025/03/19 Views:158 Category:ALGORITHM

Let's first look at the definition of merge sort Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obt

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial