简体   繁体   中英

Is it possible to get the key when it is found in array?

Is there a better way to get a key from an array if it is found in case-insensitive search?

The logic of the code I need is like below:

<?php
$search = "foo";
$array = array('Foo' => 1, 'Boo' => 2);

if (array_key_exists($search, array_map('strtolower', $array)))
    return "Foo";
?>

Approach I would like to improve:

<?php
if (array_key_exists($search, array_map('strtolower', $array)))
{
    foreach($array as $k => $v)
    {
    if ($search == strtolower($k))
        return $k;
    }
    unset ($k, $v);
}
?>
$a = ['a' => '1', 'b' => '2', 'C' => 3];
$search = 'c';

$result = array_filter($a, function($k) use ($search) {
  return strtolower($k) != $search;
}, ARRAY_FILTER_USE_KEY);

var_dump($result);
$search = "foo";
$array = array('Foo' => 1, 'Boo' => 2);

function get_value($array, $search) {
    foreach($array as $key => $value) {
        if($search === strtolower($key)) {
            return $value;
        }
    }

    return null;
}

function get_key($array, $search) {
    foreach($array as $key => $value) {
        if($search === strtolower($key)) {
            return $key;
        }
    }

    return false;
}

echo get_value($array, $search);
var_dump(get_key($array, $search));

I believe you're looking for this approach.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM