Skip to content
Advertisement

PHP Merge two array with duplicates

I have two array.

$ids = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110];
$users = [1,2,3,4,5];

for ($index = 0; $index < count($ids ); $index++) {
     echo $ids [$index] . $users [$index];
}        

My Result;

100 - 1
101 - 2
102 - 3
103 - 4
104 - 5

I would like to merge it with duplicates ids.

100 - 1
101 - 2
102 - 3
103 - 4
104 - 5
105 - 1
106 - 2
107 - 3
108 - 4
109 - 5
110 - 1

Advertisement

Answer

If your arrays are indeed this small, array_shift is a good tool. You can copy your array, pop an item off it continuously, and then re-copy the array as needed. The performance of array_shift gets worse as arrays grow large (as far as I’ve been told, but haven’t personally witnessed).

$ids = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110];
$users = [1,2,3,4,5];

// Temporary copy of users
$user_ids = [];
foreach( $ids as $id ){
    
    // If our copy is empty, reload it
    if(!$user_ids){
        $user_ids = $users;
    }
    
    // Use array_shift() to grab and remove from the front
    echo sprintf('%1$d - %2$d', $id, array_shift($user_ids)), PHP_EOL;
}

If you users is indeed linear like that, you can also use modular arithmetic to repeat things:

foreach( $ids as $idx => $id ){
    echo sprintf('%1$d - %2$d', $id, ($idx % 5) + 1 ), PHP_EOL;
}

Both demoed here: https://3v4l.org/LuRQj

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement