Yekver
Yekver

Reputation: 5195

Create mutually exclusive arrays on PHP

I have an array $used_logins with set of logins (can be large), and I need to generate an array of three unique logins like $login+rand(1, 1000); which wouldn't be in $used_logins array.

How can I do this fastly?

Upvotes: 0

Views: 319

Answers (3)

johannes
johannes

Reputation: 15989

If you can't do it in a database or such: Use the keys of $used_logins to store the data. And then check whether an element with the key exists.

$k_used_logins = array_flip($used_logins);  // Complexity is O(n)

$logins = array();
do {
    $l = $login+rand(1, 1000);
    if (!isset($k_used_logins[$l])) { // Complexity O(1)
        $logins[] = $l;
    }
} while (sizeof($logins) != 3);

Depending on the sie of the array this can be faster thant the naive way using array search each time. (One creates a copy of the array, but array_search slower than a key access)

Upvotes: 1

Rodrigo Ferreira
Rodrigo Ferreira

Reputation: 366

  1. If the logins are always generated by you, you may use a unique number in it (e.g. a timestamp). Edit: you may also append the size of the $used_logins array ($login + count($used_logins)). Of course, this only works if there are no concurrent requests (you may add a random number to avoid that).

  2. If other users may create the login, you may just check if the login already exists with the in_array() function.

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300995

If these logins are in a database, that might be the most efficient way - do a left join on 'available logins' to 'used logins' and you can filter on rows with NULLs in the right hand side to get 'unused logins'

Upvotes: 0

Related Questions