Skip to content
Related Articles

Related Articles

PHP | Program to check a string is a rotation of another string
  • Last Updated : 01 Apr, 2018

Given the two strings we have to check if one string is a rotation of another string.


Input : $string1 = "WayToCrack",
        $string2 = "CrackWayTo";
Output : Yes

Input : $string1 = "WillPower" 
        $string2 = "lliW";
Output : No.

The above problem can be easily solved in other languages by concatenating the two strings and then would check if the resultant concatenated string contains the string or not. But in PHP we will use an inbuilt function to solve the problem. The inbuilt functions used are:

  • strpos(): The function generally accepts the two parameters first one to specify the string to be searched and the other one to find in the specified string.

In PHP solution strpos() will give the last position of string if found in the specified string.

Below is the implementation of above approach

    function rotation_string($string1, $string2)
        // if both strings are not same length then stop
        if (strlen($string1) != strlen($string2))
           echo "No";
         // concatenate $string1 to itsel, if both
         // strings are of same length
         if (strlen($string1) == strlen($string2))
            $string1 = $string1.$string1;
         if (strpos($string1, $string2) > 0)
            echo "Yes";
            echo "No";
    // Driver code
    $string1 = "WayToCrack";
    $string2 = "CrackWayTo";        
    rotation_string($string1, $string2);

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :