I’m trying to make a function that is able to rotate through an array a given amount of times and then return the first index. But what I have is really slow and clunky. Take a look:
<?php
/**
* Get the current userid
* @return integer
*/
public function getCurrentUser( DateTime $startDate, DateInterval $interval, DateTime $endDate, $currentUser, $users, $rotating )
{
if ($rotating == 0)
{
return $currentUser;
}
$usrArray = array();
$dateRange = new DatePeriod( $startDate, $interval, $endDate);
// Push userIds to an array
foreach ($users as $user)
{
$usrArray[] = $user->id;
}
// Get the number of iterations from startDate to endDate
$steps = iterator_count($dateRange);
// Find the initial position of the orignal user
$key = array_search($currentUser, $usrArray);
// Set up the array so index 0 == currentUser
$usr = $usrArray;
array_splice($usr, $key);
$slice = array_slice($usrArray, $key);
$startList = array_merge($slice, $usr);
// Start rotating the array
for ($i=0; $i < $steps; $i++)
{
array_push($startList, array_shift($startList));
}
return $startList[0];
}
Here’s an Xdebug profile before the PHP script timed out.
xdebug profile
Is there a better way to figure out who is index 0 after x amount of rotations?
Your array rotation is not that slow but it can be improved .. i believe this is your rotation code
Your code
You can remove the loop replace it with mod .. the way you can still get the same results here is the solution:
Solution
You would get the same result .
Simple benchmark & Testing
Output