Created
October 24, 2019 03:55
-
-
Save tannerhodges/5318d16784f8cfc6b87281d26fb04ad0 to your computer and use it in GitHub Desktop.
Make PHP's `array_map()` behave more like JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Make PHP `array_map()` more like JavaScript. | |
* | |
* - Reverse paramaters so array comes first, callback second. | |
* - Include index as second argument to callback. | |
* | |
* @param array $arr | |
* @param function $callback | |
* @return array | |
*/ | |
function map(array $arr, $callback) { | |
return array_map($callback, $arr, range(0, count($arr) - 1)); | |
} | |
// Example | |
map(['hello', 'goodbye', 'goodnight'], function ($msg, $i) { | |
echo "$i - $msg\n"; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment