Skip to content

Instantly share code, notes, and snippets.

@eusonlito
Last active January 24, 2022 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eusonlito/0aafbf3fecd10ab7ad920df8fc1216ab to your computer and use it in GitHub Desktop.
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.
<?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