Skip to content

Instantly share code, notes, and snippets.

@scottchiefbaker
Created March 20, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottchiefbaker/3dbe9da5d60978e4dcf9 to your computer and use it in GitHub Desktop.
Save scottchiefbaker/3dbe9da5d60978e4dcf9 to your computer and use it in GitHub Desktop.
PHP functions to test if an array is associative or numeric (hash vs array)
/**
* Returns boolean if a function is an associative array
*
* @param array $array An array to test
*
* @return boolean
*/
public static function is_assoc_array($array) {
if (!is_array($array)) { return false; }
// $array = array() is not associative
if (sizeof($array) === 0) { return false; }
return array_keys($array) !== range(0, count($array) - 1);
}
/**
* Returns boolean if a function is flat/sequential numeric array
*
* @param array $array An array to test
*
* @return boolean
*/
public static function is_numeric_array($array) {
if (!is_array($array)) { return false; }
$current = 0;
foreach (array_keys($array) as $key) {
if ($key !== $current) { return false; }
$current++;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment