Converting all keys into snake case in multidimensional array in PHP
In the Snake case, we need to convert a given sentence or a word to a style of writing where all upper case characters will be replaced with lower case and all the gaps will be replaced with an underscore(_). In this article, we will see how to find the snake case of the all keys of a given array.
Here, we need to check each of the elements present in the array and then convert it to the snake case. There is one possibility that the array may contain some values whose snake case will be the same as it is. To solve this problem, two approaches are discussed below:
Approach 1: In the first approach, a function is declared where the logic for snake case conversion is defined. This function is responsible for all conversion that is upper to lower case and filling the gaps between letters by an underscore(_). Then, this function is called for each and every element present in the array. This is a recursive method to check whether the elements are already in snake case or not. If they are already in snake case then it will be as it is, else it will be converted to snake case and printed.
Example 1: This example illustrates the above approach for converting all keys into a snake case in a multidimensional array.
geek => [geek] Geek => [geek] GeeksforGeeks => [geeksfor_geeks] Geeks4Geeks => [geeks4_geeks] GeekGeekGeek => [geek_geek_geek] geek_geek => [geek_geek] Geek4 => [geek4] It is Computer Science Portal => [it_is_computer_science_portal] Technical Scripter 2022 => [technical_scripter]
Approach 2: In the second approach, a class is defined where all the array values are declared as its object. It is a little tricky here that all the objects need to be declared. After that, the input array will be generated from these objects. Finally, one function is declared to key generation and append the conversion logic. Similarly, all the values will be checked and then converted to a snake case if needed and printed. This is an object-oriented approach where the values of the input array are considered as objects initially. There may be some warning in output but that can be ignored simply.
Example 2: This example illustrates the above approach for converting all keys into a snake case in a multidimensional array.
PHP Warning:Creating default object from empty value in /home/main.php on line 16 Array ( [geeks_for_geeks] => GeeksForGeeks [gfgevent] => Array ( [technical_scripter2022] => TechnicalScripter2022 [coding_challenge] => codingChallenge [sdehiring_event] => SDEhiringEvent ) )