title: How does this recursive code to find all permutations of a string work?
body: <p>I am doing <a href="http://projecteuler.net" rel="nofollow">Project Euler</a> problems. I am currently working on the circular primes problem</p>
  
  <blockquote>
    <p>The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.</p>
    
    <p>There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.</p>
    
    <p>How many circular primes are there below one million?</p>
  </blockquote>
  
  <p>Although checking if something is primes was easy for me, I could not figure out how to get all the permutations of the numbers. After a good bit of searching for tips on an algorithm to do that, I came across a website which gave code for that in Java, which I adapted to PHP below. However, before proceeding with the problem, I would really like to understand what exactly the different bits of the code are doing, especially in the for loop. What I understand of it so far is that in the for loop, it is starting with an empty prefix and then looping through the string and adding a single element from the string to the prefix, until there is only one element left in the original string, at which point, it echoes it out. Am I understanding this correctly? If not, what am I missing?</p>
  
  <pre><code>&lt;?php
      getallcombos("","1234");
      function getallcombos($prefix,$string){
          if(strlen($string)==1){
              echo $prefix.$string."&lt;br&gt;";
          }
          $array=str_split($string);
          for($i=0;$i&lt;strlen($string);$i++){
              $newstr=substr($string,0,$i).substr($string,$i+1);
              getallcombos($prefix.$array[$i],$newstr);
          }                       
      }       
  ?&gt;
  </code></pre>