-3

I have a simple array along the lines of [2,4,7,8] and I want to change the entries into the textual equivalents eg ["two","four","seven","eight"].

I know how to convert individual numbers using the NumberFormatter class but is there a good way of doing this with an array of numbers?

2 Answers2

1

The most efficient way should be to use array_map with NumberFormatter::SPELLOUT

$nf = new NumberFormatter("en", NumberFormatter::SPELLOUT);
$arr = array_map(function($v) use ($nf) {
    return $nf->format($v);
}, $arr);
print_r($arr); // Array ( [0] => two [1] => four [2] => seven [3] => eight )
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
0

You can do it with a foreach

$numberFormatter = new NumberFormatter("en", NumberFormatter::SPELLOUT);

foreach ($array as $key=>$value){
   $array[$key] = $numberFormatter->format($value);
}

Performance comparison :

Stackoverflow - Performance of foreach, array_map with lambda and array_map with static function

GgLaPoule
  • 41
  • 6
  • 3
    Wouldnt `$array[$key] = $numberFormatter->format($value);` be simpler as you actually have the value in a variable – RiggsFolly Apr 19 '18 at 14:39
  • Yep, I made a mistake – GgLaPoule Apr 19 '18 at 14:47
  • So fix it, and maybe the last downvote will get removed. None of them were mine by the way – RiggsFolly Apr 19 '18 at 14:49
  • **Performance:** It really depends on how you bench marked it. Did you tried running this code? https://pastebin.com/vjXaytvg There is a very small difference. I don't think people would actually care about it. –  Apr 19 '18 at 14:59