函式名稱:array_search()
功能:在陣列中搜尋給定的值,並返回對應的鍵名。
用法: array_search ( mixed $needle , array $haystack [, bool $strict = false ] ) : mixed
引數:
- $needle: 要搜尋的值
- $haystack: 要搜尋的陣列
- $strict(可選): 是否進行嚴格的比較,預設為false(非嚴格比較)
返回值:
- 如果找到了匹配的鍵名,則返回對應的鍵名(字串或數字)
- 如果未找到匹配的值,則返回false(注意:返回值的型別是mixed)
示例:
<?php
$fruits = array("apple", "banana", "orange", "grape");
$key = array_search("banana", $fruits);
echo "The key of 'banana' is: " . $key; // 輸出:The key of 'banana' is: 1
$key = array_search("pear", $fruits);
echo "The key of 'pear' is: " . var_export($key, true); // 輸出:The key of 'pear' is: false
$numbers = array(2, 4, 6, 8, 10);
$strictKey = array_search(6, $numbers, true);
echo "The key of 6 (using strict comparison) is: " . $strictKey; // 輸出:The key of 6 (using strict comparison) is: 2
$strictKey = array_search("6", $numbers, true);
echo "The key of '6' (using strict comparison) is: " . var_export($strictKey, true); // 輸出:The key of '6' (using strict comparison) is: false
?>
以上示例中,首先建立了一個包含水果的陣列 $fruits
和一個包含數字的陣列 $numbers
。然後,透過呼叫 array_search()
函式來搜尋指定的值。
在第一個示例中,搜尋了值為 "banana" 的元素,返回了該元素的鍵名 1,並輸出了相應的結果。
在第二個示例中,搜尋了值為 "pear" 的元素,由於該元素不在陣列中,返回了 false,並透過 var_export()
函式將結果轉為字串輸出。
在第三個示例中,使用了嚴格的比較模式,搜尋了值為 6 的元素,返回了該元素的鍵名 2,並輸出了相應的結果。
在最後一個示例中,同樣使用了嚴格的比較模式,但搜尋的值為字串 "6",由於該元素不在陣列中且嚴格模式下型別也不匹配,返回了 false,並透過 var_export()
函式將結果轉為字串輸出。