From 7a5a29c7670794b850d9e2302331cb190b630a20 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Mon, 2 Dec 2013 20:57:24 -0500 Subject: [PATCH] Added ArrayHelper::keyExists(). --- framework/yii/helpers/BaseArrayHelper.php | 23 +++++++++++++++++++++++ tests/unit/framework/helpers/ArrayHelperTest.php | 17 +++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/framework/yii/helpers/BaseArrayHelper.php b/framework/yii/helpers/BaseArrayHelper.php index da63238..ad8cb21 100644 --- a/framework/yii/helpers/BaseArrayHelper.php +++ b/framework/yii/helpers/BaseArrayHelper.php @@ -327,6 +327,29 @@ class BaseArrayHelper } /** + * Checks if the given array contains the specified key. + * This method enhances the `array_key_exists()` function by supporting case-insensitive + * key comparison. + * @param string $key the key to check + * @param array $array the array with keys to check + * @param boolean $caseSensitive whether the key comparison should be case-sensitive + * @return boolean whether the array contains the specified key + */ + public static function keyExists($key, $array, $caseSensitive = true) + { + if ($caseSensitive) { + return array_key_exists($key, $array); + } else { + foreach (array_keys($array) as $k) { + if (strcasecmp($key, $k) === 0) { + return true; + } + } + return false; + } + } + + /** * Sorts an array of objects or arrays (with the same structure) by one or several keys. * @param array $array the array to be sorted. The array will be modified after calling this method. * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array diff --git a/tests/unit/framework/helpers/ArrayHelperTest.php b/tests/unit/framework/helpers/ArrayHelperTest.php index a2b5bee..f7410d5 100644 --- a/tests/unit/framework/helpers/ArrayHelperTest.php +++ b/tests/unit/framework/helpers/ArrayHelperTest.php @@ -303,4 +303,21 @@ class ArrayHelperTest extends TestCase ], ], $result); } + + public function testKeyExists() + { + $array = [ + 'a' => 1, + 'B' => 2, + ]; + $this->assertTrue(ArrayHelper::keyExists('a', $array)); + $this->assertFalse(ArrayHelper::keyExists('b', $array)); + $this->assertTrue(ArrayHelper::keyExists('B', $array)); + $this->assertFalse(ArrayHelper::keyExists('c', $array)); + + $this->assertTrue(ArrayHelper::keyExists('a', $array, false)); + $this->assertTrue(ArrayHelper::keyExists('b', $array, false)); + $this->assertTrue(ArrayHelper::keyExists('B', $array, false)); + $this->assertFalse(ArrayHelper::keyExists('c', $array, false)); + } }