I have 2 arrays ($scores and $players). $scores description: key -> playerId value -> score $players key -> playerId value -> playerName Is there a better way than this to replace keys of $scores with values from $players? PHP: <?php//playerId => score$scores = [10 => 34994, 12 => 23848, 13 => 48939];//playerId => playerName$players = [10 => 'Muqsit', 12 => 'NotMuqsit', 13 => 'entity303'];$res = [];foreach ($players as $k => $v) { $res[$v] = $scores[$k];}//$res = ['Muqsit' => 34994, 'NotMuqsit' => 23848, 'entity303' => 48939];
Why not use a two dimensional array with playerID as the key, and an array of name and score as the value? Edit: since your unique ID could just be the players name, do you even need playerID? If so, I'd use the player name (or a hash) as the key anyway... but it depends what you are trying to achieve.
Your code timing (microtime): 5.0067901611328 My code timing (microtime): 2.3841857910156 PHP: <?php//playerId => score$scores = [10 => 34994, 12 => 23848, 13 => 48939];//playerId => playerName$players = [10 => 'Muqsit', 12 => 'NotMuqsit', 13 => 'entity303'];foreach ($scores as $k => &$v){ $v = $players[$k];} This is much faster because you're passing by reference rather than value, basically meaning it's real value instead of a copy (I guess you know that already).
This is another method you could use: PHP: <?php//playerId => score$scores = [10 => 34994, 12 => 23848, 13 => 48939];//playerId => playerName$players = [10 => 'Muqsit', 12 => 'NotMuqsit', 13 => 'entity303'];$res = array_combine(array_keys($players), array_values($scores)); Can't get any faster than this, m8.