Skip to content

Instantly share code, notes, and snippets.

@garvin
Last active May 14, 2018 20:38
Show Gist options
  • Save garvin/6ed79cb64da3891c64f015c4ee198a5b to your computer and use it in GitHub Desktop.
Save garvin/6ed79cb64da3891c64f015c4ee198a5b to your computer and use it in GitHub Desktop.
Quick & dirty is-array-associative test
/**
* Test whether/not $array is associative
*
* Got annoyed when I saw a coworker using the accepted answer at http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential?page=1&tab=active#tab-top
* It seems overly complicated, and fails if the linear array's keys aren't contiguous (as do several other solutions I found).
*
* Sample test arrays:
* ----------------------------------------
*
* $empty_array = array ( );
* $linear_array = array ( 0 => 'first', 1 => 'second', 2 => 'third' );
* $associative_array = array ( 'a' => 'apple', 'b' => 'banana', 'c' => 'cherry' );
* $linear_array_with_non_contiguous_indexes = array ( 2 => 'foo', 42 => 'bar' );
* $associative_array_with_integer_keys = array ( 0 => 'dread', 'i' => 'am the law' );
*
* @param array $array
* @return boolean
*/
function is_associative_array(array $array) {
foreach (array_keys($array) as $key) {
if (is_string($key)) {
return true;
}
}
return false;
}
@garvin
Copy link
Author

garvin commented May 14, 2018

Wonder if this should return true if the array is empty? Indeterminate at that point, though...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment