phparraysreplacecpu-wordsnakecasing

Convert all elements in a flat array containing multi-word values to snake_case


I've got this array:

$all_regions = [
    'Sidebar first',
    'Sidebar second',
]

It should become:

[
    'sidebar_first',
    'sidebar_second,
]

Solution

  • foreach ($all_regions as $key => $value){
       $all_regions[$key] = strtolower(str_replace(' ', '_', $value));
    }
    

    php.net - str_replace()

    Edit

    Even better would be the following (I think), because it will be faster because of the internal value pointer. (I will benchmark this)

    foreach ($all_regions as &$value){
       $value = strtolower(str_replace(' ', '_', $value));
    }