array_search()函數(shù)用來在數(shù)組中搜索給定值,并返回對應的鍵名,而array_keys()函數(shù)用來獲取數(shù)組中所有給定值的鍵名。下面是它們的用法示例:
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";
}
在這兩個示例中,我們首先創(chuàng)建了一個包含水果的數(shù)組$fruits。然后我們使用array_search()函數(shù)找到了值為"orange"的鍵名,并使用array_keys()函數(shù)找到了所有值為"banana"的鍵名。最后根據(jù)返回結果輸出相應的信息。