最近在用php寫一段代碼時,要用到判斷某值是否在另外一組值中。而in_array 函數就是用來檢查數組中是否存在某個值 。直接通過概念理解比較模糊,可以通過具體例子瞭解其作用。
文法:
bool in_array( mixed needle, array array [, bool strict] )
參數說明:
| 參數 |
說明 |
| needle |
需要在數組中搜尋的值,如果是字串,則區分大小寫 |
| array |
需要檢索的數組 |
| strict |
可選,如果設定為 TRUE ,則還會對 needle 與 array 中的實值型別進行檢查 |
例1:
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
以上代碼的執行結果是:
Got Irix
第二個條件失敗,因為 in_array() 是區分大小寫。
例2:
<?php
$europe = array("美國","英國","法國","德國","意大利","西班牙","丹麥");
if (in_array("美國",$europe)) {
echo "True";
}
?>
同上面一樣,執行結果為True 。
例3:嚴格類型檢查例子
<?php
$a = array('1.10', 12.4, 1.13);
if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check ";
}
if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check ";
}
?>
其輸出結果是:
1.13 found with strict check
例4:數組中套用數組
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found ";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found ";
}
if (in_array('o', $a)) {
echo "'o' was found ";
}
?>
其輸出結果為:
'ph' was found
'o' was found
其具體用法如下:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
在 haystack 中搜尋 needle,如果沒有設定 strict 則使用寬鬆的比較。
註:自php5.4以後。數組定義由array()換成了array[] 。