Created
January 15, 2017 17:33
-
-
Save obiPlabon/1a4b86349b66b109652740ebf4fdcb2f to your computer and use it in GitHub Desktop.
PHP custom array mapping function which supports key/index
This file contains hidden or 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 | |
| /** | |
| * PHP default array map function doesn't provide access to array item key | |
| * So there is no way to map array based on some condition which depends on | |
| * array item key. And that's why array_mapx is here to help you in that case. | |
| * @param array $arr Array that is going to be mapped | |
| * @param callable $callback Callback function to map array $a | |
| * @param boolean $preserve_keys To maintain the old keys | |
| * @return array Mapped array | |
| */ | |
| function array_mapx(array $arr, callable $callback, $preserve_keys = true) { | |
| $r = []; | |
| while($k = key($arr)) { | |
| if ($preserve_keys) { | |
| $r[$k] = $callback(current($arr), $k); | |
| } else { | |
| array_push($r, $callback(current($arr), $k)); | |
| } | |
| next($arr); | |
| } | |
| return $r; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment