Related link: http://dereksivers.com/src/recursive.phps
Tiny little satisfying bit of PHP code: recursively doing something to every value in an array.
I use PHP arrays a LOT. Everywhere. All the time. So when I needed to go do something to every value inside an array, it was one of those satisfying 60-second brain-teasers.
(In this example, below, I’m encoding the strings into UTF-8 format, but it could be any function at all.)
# recursively convert every value in array to UTF-8
foreach($array as $key=>$value)
$value = (is_scalar($value)) ? mb_convert_encoding($value, 'UTF-8') : array_to_utf8($value);
$array[$key] = $value;
See it pretty at: recursive.php
Just thought I’d share it with the O’Reilly readers in case it’s of any use to you.
Got another use for this you’d like to share? Another approach? An easier way?