Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a string N times in PHP

Tags:

string

php

I'm looking for a way to rotate a string to the left N times. Here are some examples:

Let the string be abcdef

  • if I rotate it 1 time I want bcdefa
  • if I rotate it 2 time I want cdefab
  • if I rotate it 3 time I want defabc
  • .
  • .
  • If I rotate the string its string length times, I should get back the original string.
like image 777
gameover Avatar asked Nov 28 '22 23:11

gameover


1 Answers

 $rotated = substr($str, $n) . substr($str, 0, $n);
like image 86
user187291 Avatar answered Dec 08 '22 00:12

user187291