Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

You can use class below to convert all keys into snake case in given array.


Class


class ArrayKeyCaseConverter
{
public function snakeCase(array $array): array
{
return array_map(
function($item) {
if (is_array($item)) {
$item = $this->snakeCase($item);
}

return $item;
},
$this->doSnakeCase($array)
);
}

private function doSnakeCase(array $array): array
{
$result = [];

foreach ($array as $key => $value) {
$key = strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $key));

$result[$key] = $value;
}

return $result;
}
}

Input


$in = [
'jolly' => 'jolly',
'Jolly' => 'Jolly',
'JOLLY' => 'JOLLY',
'jollyGood' => 'jollyGood',
'JollyGood' => 'JollyGood',
'Jolly1' => [
'Jolly',
],
'Jolly2Jolly' => [
'jolly' => 'jolly',
'Jolly' => 'Jolly',
'JOLLY' => 'JOLLY',
'jollyGood' => 'jollyGood',
'JollyGood' => 'JollyGood',
'JollyJollyJolly' => [
'HiHi' => 'HiHi',
'be_be' => 'be_be',
],
],
];

Output


Array
(
[jolly] => Jolly
[j_o_l_l_y] => JOLLY
[jolly_good] => JollyGood
[jolly1] => Array
(
[0] => Jolly
)
[jolly2_jolly] => Array
(
[jolly] => Jolly
[j_o_l_l_y] => JOLLY
[jolly_good] => JollyGood
[jolly_jolly_jolly] => Array
(
[hi_hi] => HiHi
[be_be] => be_be
)
)
)