Created
March 20, 2015 16:59
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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