Is there a more concise way of rotating an array leftwards X times than this?
for($i = 0; $i < $x; $i++) {
array_push($array,array_shift($array));
}
Is there a more concise way of rotating an array leftwards X times than this?
for($i = 0; $i < $x; $i++) {
array_push($array,array_shift($array));
}
$a=array_merge(array_slice($a,$x), array_slice($a,0,$x));
It’s better readable (IMHO), but slightly slower.
set_time_limit(0);
class Stopwatch
{
private $_starttime;
function __construct() {}
public function start()
{
$mtime = microtime();
list($usec, $sec) = split(' ', $mtime);
$this->_starttime = (float)$usec + (float)$sec;
}
public function stop()
{
$mtime = microtime();
list($usec, $sec) = split(' ', $mtime);
return (((float)$usec + (float)$sec) - (float)$this->_starttime);
}
}
$s=new StopWatch;
$x=2;
$s->start();
for ($j=0;$j<100000;$j++) {
$a=array(1,2,3,4,5);
$a=array_merge(array_slice($a,$x), array_slice($a,0,$x));
}
echo 'Method 1: ', $s->stop(), "\
";
$s->start();
for ($j=0;$j<100000;$j++) {
$a=array(1,2,3,4,5);
for ($i=0; $i<$x; $i++) {
array_push($a,array_shift($a));
}
}
echo 'Method 2: ', $s->stop(), "\
";
/*
Method 1: 0.32495498657227
Method 2: 0.22844004631042
*/