PHP

PHP中array_search()与array_keys()怎么使用

小亿
96
2024-04-02 20:17:58
栏目: 编程语言

array_search()函数用来在数组中搜索给定值,并返回对应的键名,而array_keys()函数用来获取数组中所有给定值的键名。下面是它们的用法示例:

array_search()示例:

$fruits = array("apple", "banana", "orange", "grape");
$key = array_search("orange", $fruits);
if($key !== false) {
    echo "The key of 'orange' is: " . $key;
} else {
    echo "The value 'orange' was not found in the array";
}

array_keys()示例:

$fruits = array("apple", "banana", "orange", "banana");
$keys = array_keys($fruits, "banana");
if(!empty($keys)) {
    echo "The keys of 'banana' are: " . implode(", ", $keys);
} else {
    echo "The value 'banana' was not found in the array";
}

在这两个示例中,我们首先创建了一个包含水果的数组$fruits。然后我们使用array_search()函数找到了值为"orange"的键名,并使用array_keys()函数找到了所有值为"banana"的键名。最后根据返回结果输出相应的信息。

0
看了该问题的人还看了