Are you new? Read the FAQ and catch up on!
316 views

Rotate a string N times in PHP

(copied from a question in Stack Overflow)

This is a way to rotate a string N times. For example:

Let the string be abcdef

  • if I rotate it 1 time I want bcdefa
  • if I rotate it 2 times I want cdefab
  • if I rotate it 3 times I want defabc
  • ...
  • If I rotate the string its string length times, I should get back the original string.

The following code achieves this in a single line:

PHP
  1. $rotated = substr($str, $n) . substr($str, 0, $n);
  2.  

­

Tags: PHP strings

Embed: