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"的鍵名。最后根據返回結果輸出相應的信息。