Last active
January 24, 2022 16:22
-
-
Save eusonlito/0aafbf3fecd10ab7ad920df8fc1216ab to your computer and use it in GitHub Desktop.
PHP helper to recursive iterate over an array. Method will send `$value` and `$key` to callback. `$values_only` option allow to send only final values to callback.
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 declare(strict_types=1); | |
/** | |
* @param array $array | |
* @param callable $callback | |
* @param bool $values_only = true | |
* | |
* @return array | |
*/ | |
public function arrayMapRecursive(array $array, callable $callback, bool $values_only = true): array | |
{ | |
$map = function ($value, $key) use ($callback, $values_only) { | |
if (is_array($value) === false) { | |
return $callback($value, $key); | |
} | |
if ($values_only) { | |
return $this->arrayMapRecursive($value, $callback, $values_only); | |
} | |
return $this->arrayMapRecursive($callback($value, $key), $callback, $values_only); | |
}; | |
return array_combine($keys = array_keys($array), array_map($map, $array, $keys)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment