logo CodeStepByStep logo


Language/Type: PHP recursion string return

Write a recursive function named index_of that accepts two Strings $s1 and $s2 as parameters and that returns the starting index of the first occurrence of the second String $s2 inside the first String $s1, or -1 if $s2 is not found in $s1. The table below shows several calls to your function and their expected return values. If $s2 is the empty String, always return 0 regardless of the contents of $s1. If $s2 is longer than $s1, it of course cannot be contained in $s1 and therefore your function would return -1 in such a case. Notice that case matters; the last example returns -1.

Call Value Returned
index_of("Barack Obama", "Bar") 0
index_of("foo", "foo") 0
index_of("Stanford CS", "ford") 4
index_of("Barack Obama", "ack") 3
index_of("Barack Obama", "a") 1
index_of("sandwich", "") 0
index_of("Barack Obama", "McCain") -1
index_of("Barack Obama", "ACK") -1


  • Do not declare any global variables.
  • Do not use any loops; you must use recursion.
  • Do not use any auxiliary data structures (e.g. arrays) to this problem.
  • You can declare as many primitive variables (e.g. integers) as you like.
  • You are allowed to define other "helper" functions if you like; they are subject to these same constraints.
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.