One of PHP’s most powerful features are arrays and the multitude of functions available to interact with and manipulate them. Arrays can be indexed by integers as well as string, known as an associative array. Instead of looping through the array with foreach and assigning the key to another array, you can easily use array_keys() to grab the keys from the array, regardless if it”s associative or not:
If you were to print_r($array_keys) you would see something like this:
Using array_keys() is the equivalent of doing something like this:
Depending on the circumstances, I will still do it that way from time to time, especially in situations where I have other data manipulation going on and would already be looping through the data. An interesting observation is that when I compared array_keys() against the foreach() over 1,000,000 iterations, they both ran in roughly the same amount of time with no clear winner. The shorter syntax is obviously an advantage and if I had to guess, PHP is probably just performing a foreach() loop internally when calling array_keys().