This question already has an answer here:
To start off, let's look at the arrays -
$array1 = array('user@email.com','user2@email.com','user3@email.com'); // Imagine this has over a million users
$array2 = array('domain1.com','domain2.com'); // This may have between 10-20 domains
What I want to do is loop through the users and continuously assign a domain in the second array to a user in the first array. It should look like this when completed -
$finished = array('user@email.com' => 'domain1.com', 'user2@email.com' => 'domain2.com', 'user3@email.com' => 'domain1.com');
How can I loop through $array1
and sequentially assign a domain from $array2
to each user?
This is mind boggling me right now.
Just FYI array_combine() from the "Duplicate Answer" is incorrect to this answer. The correct answer is below. If $array1 has 5,000,000 emails in it and $array2 has 10 domains in it, the finished array would only give the first 10 items in the array a corresponding domain. Those who marked it duplicate did not read the full description, or do not understand PHP.
</div>
Similar to Barmar's, but using the key:
$count = count($array2);
foreach($array1 as $key => $value) {
$finished[$value] = $array2[$key % $count];
}
This works with your posted arrays, however if you have lets say all even or all odd keys in $array1
this would bomb, also with an associative array.
Increment an index in $array2
modulo its size as you assign values.
$index = 0;
$finished = array();
foreach ($array1 as $email) {
$finished[$email] = $array2[$index];
$index = ($index + 1) % count($array2);
}
Make a loop over the larger set. Keep a secondary index variable, and each iteration, increment it, then set it to its value modulo the size of the smaller set. Use this secondary index as the index into your second set to assign to the element from the first set.