Skip to content

Instantly share code, notes, and snippets.

@tannerhodges
Created October 24, 2019 03:55
Show Gist options
  • Save tannerhodges/5318d16784f8cfc6b87281d26fb04ad0 to your computer and use it in GitHub Desktop.
Save tannerhodges/5318d16784f8cfc6b87281d26fb04ad0 to your computer and use it in GitHub Desktop.
Make PHP's `array_map()` behave more like JavaScript.
<?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