note 89191 modified in function.array-key-exists by danbrown
| From: | danbrown@php.net | Date: | Thu, 26 Feb 2009 00:48:35 +0000 |
| Subject: | note 89191 modified in function.array-key-exists by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-151139@lists.php.net to get a copy of this message | ||
Below is a more efficient and useful case-insensitive array_key_exists function. More useful in the
sense that it returns the matching key.
<?php
/**
* Case insensitive version of array_key_exists.
* Returns the matching key on success, else false.
*
* @param string $key
* @param array $search
* @return string|false
*/
function array_key_exists_nc($key, $search) {
if (array_key_exists($key, $search)) {
return $key;
}
if (!(is_string($key) && is_array($search) && count($search))) {
return false;
}
$key = strtolower($key);
foreach ($search as $k => $v) {
if (strtolower($k) == $key) {
return $k;
}
}
return false;
}
/* Test code: */
$array = array(
'taste' => 'sweet',
'cOlOr' => 'yellow',
'foo',
'bar',
);
$keys = array(
'Color',
'google',
0,
);
foreach ($keys as $key) {
print "\t$key: "; var_dump(array_key_exists_nc($key, $array));
}
/* Output:
Color: string(5) "cOlOr"
google: bool(false)
0: int(0)
*/
?>
--was--
Below is a more efficient and useful case-insensitive array_key_exists function. More useful in the
sense that it returns the matching key.
/**
* Case insensitive version of array_key_exists.
* Returns the matching key on success, else false.
*
* @param string $key
* @param array $search
* @return string|false
*/
function array_key_exists_nc($key, $search) {
if (array_key_exists($key, $search)) {
return $key;
}
if (!(is_string($key) && is_array($search) && count($search))) {
return false;
}
$key = strtolower($key);
foreach ($search as $k => $v) {
if (strtolower($k) == $key) {
return $k;
}
}
return false;
}
/* Test code: */
$array = array(
'taste' => 'sweet',
'cOlOr' => 'yellow',
'foo',
'bar',
);
$keys = array(
'Color',
'google',
0,
);
foreach ($keys as $key) {
print "\t$key: "; var_dump(array_key_exists_nc($key, $array));
}
/* Output:
Color: string(5) "cOlOr"
google: bool(false)
0: int(0)
*/
http://php.net/manual/en/function.array-key-exists.php