7kasper
7kasper

Reputation: 35

PHP Loop through dynamic array

I have a webapplication with a php backend. At a certain interval checks need to be run on all users. Running these checks takes some time, more importantly: they should not be executed on non-existing users. The users are received from a database and can change mid-way through running the checks. My current solution is:

<?php 
require_once 'databaseUtils.php';

$users = getUsersFromDatabase();
//Sample:
while(true) {
  foreach(GetUsers() as &$user) {
    //I'd rather not:
    if(checkIfUserIsInDatabase($user) {
       var_dump($user);
       sleep(1); //Checking takes time...
    }
  }
  echo "Going again in 5s!";
  sleep(5); //Interval
}

function GetUsers() {
  return $users;
}

//Called from outside
function removeUser($user) {
  global $users;
  removeUserFromDatabase($user);
  if(($key = array_search($user, $users)) !== false) {
      unset($users[$key]);
  }
}
?>

But I'm still looping needlessly through the user that isn't realy in the GetUsers() anymore. Is there a way to loop through all values of an array in which elements can get deleted from outside?

Upvotes: 1

Views: 1104

Answers (2)

sevavietl
sevavietl

Reputation: 3812

Firstly, you might need to consider to rework your entire business logic.

Do not use endless loops (while(true)) and global variables (global $users).

To loop through all users you can use generator concept and retrieve existent users one by one. So you will get only the next user from the database during each iteration:

function getUsersFromDatabase($db)
{
    $id = 0;

    while (($user = $db->query("SELECT * FROM `users` WHERE `id` > $id LIMIT 1"))) {
        yield $user;
        $id = $user->id;
    }
}

foreach (getUsersFromDatabase($db) as $user) {
    checkUser($user);
}

I do not know your framework or DB adapter details, so the code snippet is generic and should be considered as pseudo code.

Upvotes: 1

Nick Kadutskyi
Nick Kadutskyi

Reputation: 188

If you want to check each user if he is still in the database, you will need to query his information from database, so it will take more efforts than checking each item in array (if it is not more resource spending).

But I will suggest to get users in smaller portions instead of all users. And check portion by portion.

Upvotes: 1

Related Questions