Helping PHP
February 22, 2009
Recently while working on a project, I discovered that PHP has no built in way to detect associative arrays. After a few searches I found that several people had put some functions together that would do the job but most just seemed a little bloated or slow. So, I decided that I would take a crack at it myself.
First thing to do is to create the function. I chose to call it is_assoc(), because the other built in type checking function start with “is_”. We also have to pass the variable we want to check, I’m calling it $_array.
function is_assoc($_array) { } // is_assoc
Above everything else an associative array is just a type of array. So, the first thing we do is check to make sure $_array is in fact an array.
if (is_array($_array) == false) { return false; } // if
Now that we know we have an array we get to the tricky part. Making sure that that array is associative. If you’ve already figured the next part out awesome, it stumped me for a few minutes.
When you create and array in PHP each value gets an index (0, 1, 2, 3…). When you create an associative array you are setting the index or key manually (item, next_item, or whatever you use). So, if we could get an indexed array of just the keys of the array we are checking we could determine if they are from and indexed or an associative array. Lucky for us PHP has a built in function just for that, array_keys(). It returns an indexed array of all the keys of what ever array you pass it.
So, all we have to do now is loop through each item of the keys array and check to see if the index of the item matched the value of the key it represents. If they all match we have an indexed array. If any of them are different we have an associative array.
foreach (array_keys($_array) as $key => $value) { if ($key !== $value) { return true; } // if } // foreach
So, that means that anytime the keys of the test array are not in sequential order from start to finish we have an associative array. If we have an indexed array it will loop through each item and keep going, so we end with a return false.
return false;
Review:
If you pass a really large array to this function it could take a while to process and may even hang. Let me know how this function works for you, especially if you make any changes. I would be very interested to see what you come up with.
Here’s the full version of the function:
/* * is_assoc($_array) * * PHP does not have this function * * Returns true if $_array is an associative array. */ function is_assoc($_array) { if (is_array($_array) == false) { return false; } // if foreach (array_keys($_array) as $key => $value) { if ($key !== $value) { // check if keys are a sequential numeric sequence return true; } // if } // foreach return false; } // is_assoc