mirror of
https://github.com/yiisoft/yii2.git
synced 2025-12-19 07:07:58 +08:00
Added isAssociative() and isIndexed() to yii\helpers\ArrayHelper
This commit is contained in:
@@ -490,4 +490,71 @@ class BaseArrayHelper
|
||||
|
||||
return $d;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the given array is an associative array.
|
||||
*
|
||||
* An array is associative if all its keys are strings. If `$allStrings` is false,
|
||||
* then an array will be treated as associative if at least one of its keys is a string.
|
||||
*
|
||||
* Note that an empty array will NOT be considered associative.
|
||||
*
|
||||
* @param array $array the array being checked
|
||||
* @param boolean $allStrings whether the array keys must be all strings in order for
|
||||
* the array to be treated as associative.
|
||||
* @return boolean whether the array is associative
|
||||
*/
|
||||
public static function isAssociative(array $array, $allStrings = true)
|
||||
{
|
||||
if (empty($array)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($allStrings) {
|
||||
foreach ($array as $key => $value) {
|
||||
if (!is_string($key)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
foreach ($array as $key => $value) {
|
||||
if (is_string($key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a value indicating whether the given array is an indexed array.
|
||||
*
|
||||
* An array is indexed if all its keys are integers. If `$consecutive` is true,
|
||||
* then the array keys must be a consecutive sequence starting from 0.
|
||||
*
|
||||
* Note that an empty array will be considered indexed.
|
||||
*
|
||||
* @param array $array the array being checked
|
||||
* @param boolean $consecutive whether the array keys must be a consecutive sequence
|
||||
* in order for the array to be treated as indexed.
|
||||
* @return boolean whether the array is associative
|
||||
*/
|
||||
public static function isIndexed(array $array, $consecutive = false)
|
||||
{
|
||||
if (empty($array)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($consecutive) {
|
||||
return array_keys($array) === range(0, count($array) - 1);
|
||||
} else {
|
||||
foreach ($array as $key => $value) {
|
||||
if (!is_integer($key)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user