0

If I have two strings, for example "123456789" and "135792468", and I want to know if they are a reordering of each other, is there a function in PHP like function is_reorder(str1, str2) where I can input is_reorder(123456789, 135792468) and have it return TRUE because 123456789 is just 135792468 in a different order?

If there is no built-in function for this, how can I do it?

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
Hexer
  • 51
  • 7

2 Answers2

2

Here's a method:

$string1 = '123456789';
$string2 = '135792468';

$stringParts1 = str_split($string1);
sort($stringParts1);

$stringParts2 = str_split($string2);
sort($stringParts2);

if($stringParts1 == $stringParts2){
echo 'strings are a reorder';
}else{
echo 'strings are not a reorder'; 
};

What this does is take the strings apart, sort the characters alphabetically and then compare them. Here's an example

EDIT: the implode() function was removed because unnecessary.

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58
  • I think the implode step isn't necessary. After sorting the arrays of characters, you should be able to check if they are equal without joining them back together. – Don't Panic Jul 17 '18 at 22:34
1

Sort both the strings and compare to see if both are equal - if they are equal, then these strings are reorder of one another. There is no built-in function for this in php as far as I know. Even if there were, that would use sorting I can assure.

Any standard sorting algorithm will do. Now if you want efficiency, you can use counting sort to sort the strings which is O(n), this way you even have a shortcut - count the frequency of each characters and try to compare the number of occurrence of each characters in both strings if they are equal or not.

Kaidul
  • 15,409
  • 15
  • 81
  • 150