function arrayIsAssociative($myArray) {foreach (array_keys($myArray) as $ind => $key) {if (!is_numeric($key) || (isset($myArray[$ind + 1]) && $myArray[$ind + 1] != $key + 1)) {return true;}}return false;}// this will only return true if all the keys are numeric AND sequential, which// is what you get when you define an array like this:// array("a", "b", "c", "d", "e");
或
function arrayIsAssociative($myArray) {$l = count($myArray);for ($i = 0; $i < $l, ++$i) {if (!isset($myArray[$i])) return true;}return false;}// this will return a false positive on an array like this:$x = array(1 => "b", 0 => "a", 2 => "c", 4 => "e", 3 => "d");
function array_isassociative($array){// Create new Array, Make it the same size as the input array$compareArray = array_pad(array(), count($array), 0);
// Compare the two array_keysreturn (count(array_diff_key($array, $compareArray))) ? true : false;
}
/*** Checks if an array is associative by utilizing REGEX against the keys* @param $arr <array> Reference to the array to be checked* @return boolean*/private function isAssociativeArray( &$arr ) {return (bool)( preg_match( '/\D/', implode( array_keys( $arr ) ) ) );}
//! Check whether the input is an array whose keys are all integers./*!\param[in] $InputArray (array) Input array.\return (bool) \b true iff the input is an array whose keys are all integers.*/function IsArrayAllKeyInt($InputArray){if(!is_array($InputArray)){return false;}
if(count($InputArray) <= 0){return true;}
return array_unique(array_map("is_int", array_keys($InputArray))) === array(true);}
案例2:所有键都是字符串。
说明:对于空数组,此函数也返回true。
//! Check whether the input is an array whose keys are all strings./*!\param[in] $InputArray (array) Input array.\return (bool) \b true iff the input is an array whose keys are all strings.*/function IsArrayAllKeyString($InputArray){if(!is_array($InputArray)){return false;}
if(count($InputArray) <= 0){return true;}
return array_unique(array_map("is_string", array_keys($InputArray))) === array(true);}
有些键是字符串,有些键是数字/整数。
说明:对于空数组,此函数也返回true。
//! Check whether the input is an array with at least one key being an integer and at least one key being a string./*!\param[in] $InputArray (array) Input array.\return (bool) \b true iff the input is an array with at least one key being an integer and at least one key being a string.*/function IsArraySomeKeyIntAndSomeKeyString($InputArray){if(!is_array($InputArray)){return false;}
if(count($InputArray) <= 0){return true;}
return count(array_unique(array_map("is_string", array_keys($InputArray)))) >= 2;}
//! Check whether the input is an array whose keys are numeric, sequential, and zero-based./*!\param[in] $InputArray (array) Input array.\return (bool) \b true iff the input is an array whose keys are numeric, sequential, and zero-based.*/function IsArrayKeyNumericSequentialZeroBased($InputArray){if(!is_array($InputArray)){return false;}
if(count($InputArray) <= 0){return true;}
return array_keys($InputArray) === range(0, count($InputArray) - 1);}
array("fish and chips" => "b");array("" => "b"); // An empty string is also a string.array("stackoverflow_email@example.com" => "b"); // Strings may contain non-alphanumeric characters.array("stack\t\"over\"\r\nflow's cool" => "b"); // Strings may contain special characters.array('$tα€k↔øv∈rflöw⛄' => "b"); // Strings may contain all kinds of symbols.array("functіon" => "b"); // You think this looks fine? Think again! (see https://stackoverflow.com/q/9246051/1402846)array("ま말轉转ДŁ" => "b"); // How about Japanese/Korean/Chinese/Russian/Polish?array("fi\x0sh" => "b"); // Strings may contain null characters.array(file_get_contents("https://www.google.com/images/nav_logo114.png") => "b"); // Strings may even be binary!
array("13" => "b");array("-13" => "b"); // Negative, ok.
但是这些数组的键是字符串:
array("13." => "b");array("+13" => "b"); // Positive, not ok.array("-013" => "b");array("0x1A" => "b"); // Not converted to integers even though it's a valid hexadecimal number.array("013" => "b"); // Not converted to integers even though it's a valid octal number.array("18446744073709551616" => "b"); // Not converted to integers as it can't fit into a 64-bit integer.
<?php/*** Since PHP stores all arrays as associative internally, there is no proper* definition of a scalar array.** As such, developers are likely to have varying definitions of scalar array,* based on their application needs.** In this file, I present 3 increasingly strict methods of determining if an* array is scalar.** @author David Farrell <DavidPFarrell@gmail.com>*/
/*** isArrayWithOnlyIntKeys defines a scalar array as containing* only integer keys.** If you are explicitly setting integer keys on an array, you* may need this function to determine scalar-ness.** @param array $a* @return boolean*/function isArrayWithOnlyIntKeys(array $a){if (!is_array($a))return false;foreach ($a as $k => $v)if (!is_int($k))return false;return true;}
/*** isArrayWithOnlyAscendingIntKeys defines a scalar array as* containing only integer keys in ascending (but not necessarily* sequential) order.** If you are performing pushes, pops, and unsets on your array,* you may need this function to determine scalar-ness.** @param array $a* @return boolean*/function isArrayWithOnlyAscendingIntKeys(array $a){if (!is_array($a))return false;$prev = null;foreach ($a as $k => $v){if (!is_int($k) || (null !== $prev && $k <= $prev))return false;$prev = $k;}return true;}
/*** isArrayWithOnlyZeroBasedSequentialIntKeys defines a scalar array* as containing only integer keys in sequential, ascending order,* starting from 0.** If you are only performing operations on your array that are* guaranteed to either maintain consistent key values, or that* re-base the keys for consistency, then you can use this function.** @param array $a* @return boolean*/function isArrayWithOnlyZeroBasedSequentialIntKeys(array $a){if (!is_array($a))return false;$i = 0;foreach ($a as $k => $v)if ($i++ !== $k)return false;return true;}
<?php
function method_1(Array &$arr) {return $arr === array_values($arr);}
function method_2(Array &$arr) {for (reset($arr), $i = 0; key($arr) !== $i++; next($arr));return is_null(key($arr));}
function method_3(Array &$arr) {return array_keys($arr) === range(0, count($arr) - 1);}
function method_4(Array &$arr) {$idx = 0;foreach( $arr as $key => $val ){if( $key !== $idx )return FALSE;$idx++;}return TRUE;}
function benchmark(Array $methods, Array &$target){foreach($methods as $method){$start = microtime(true);for ($i = 0; $i < 1000; $i++)$dummy = call_user_func($method, $target);
$end = microtime(true);echo "Time taken with $method = ".round(($end-$start)*1000.0,3)."ms\n";}}
$targets = ['Huge array' => range(0, 30000),'Small array' => range(0, 1000),];$methods = ['method_1','method_2','method_3','method_4',];foreach($targets as $targetName => $target){echo "==== Benchmark using $targetName ====\n";benchmark($methods, $target);echo "\n";}
结果:
==== Benchmark using Huge array ====Time taken with method_1 = 5504.632msTime taken with method_2 = 4509.445msTime taken with method_3 = 8614.883msTime taken with method_4 = 2720.934ms
==== Benchmark using Small array ====Time taken with method_1 = 77.159msTime taken with method_2 = 130.03msTime taken with method_3 = 160.866msTime taken with method_4 = 69.946ms
function isAssoc($arr){// Is it set, is an array, not empty and keys are not sequentialy numeric from 0return isset($arr) && is_array($arr) && count($arr)!=0 && array_keys($arr) !== range(0, count($arr) - 1);}
/*** Determines if an array is associative.** An array is "associative" if it doesn't have sequential numerical keys beginning with zero.** @param array $array* @return bool*/public static function isAssoc(array $array){$keys = array_keys($array);
return array_keys($keys) !== $keys;}
/*** Tests if an array is an associative array.** @param array $array An array to test.* @return boolean True if the array is associative, otherwise false.*/function is_assoc(array &$arr) {// don't try to check non-arrays or empty arraysif (FALSE === is_array($arr) || 0 === ($l = count($arr))) {return false;}
// shortcut by guessing at the beginningreset($arr);if (key($arr) !== 0) {return true;}
// shortcut by guessing at the endend($arr);if (key($arr) !== $l-1) {return true;}
// rely on php to optimize test by reference or fast comparereturn array_values($arr) !== $arr;}
/*iszba - Is Zero Based Array
Detects if an array is zero based or not.
PARAMS:$chkvfncCallback in the loop allows to check the values of each element.Signature:bool function chkvfnc($v);return:true continue loopingfalse stop looping; iszba returns false too.
NOTES:○ assert: $array is an array.○ May be memory efficient;it doesn't get extra arrays via array_keys() or ranges() into the function.○ Is pretty fast without a callback.○ With callback it's ~2.4 times slower.*/function iszba($array, $chkvfnc=null){
$ncb = !$chkvfnc;$i = 0;
foreach($array as $k => $v){if($k === $i++)if($ncb || $chkvfnc($v))continue;
return false;}
return true;}
$y= array(5);$y["0x"]="n";$y["vbg"]="12132";$y[1] = "k";
var_dump($y); //this will output 4 element array
echo "</br>" .$y["0x"]."</br>".$y[0];
for($x=0;$x<sizeof($y);$x++){ // this will output all index elements & gives error after thatecho "</br> index elements ".$y[$x];}
function AssocTest(&$arr){if(is_array($arr)){
reset($arr); // reset pointer to first element of array
if(gettype(key($arr)) == "string"){ //get the type(nature) of first element keyreturn true;}else{return false;}}else{return false;}}
您可以将其用作正常功能
echo(AssocTest($y)? "Associative array": "Not an Associative array/ Not an array at all");
$y["0"]="n";$y["1"]="12132";$y["22"] = "k";
//both will get the same outputecho "<br/> s0 ".$y["22"];echo "<br/> s0 ".$y[22];
for($x=0;$x<count($y);$x++){echo "<br/> arr ".$y[$x]; // this will output up to 2nd element and give an error after
}