本文實例講述了PHP使用in_array函數檢查數組中是否存在某個值的方法。分享給大家供大家參考。具體分析如下:
PHP使用in_array()函數檢查數組中是否存在某個值,如果存在則返回 TRUE ,否則返回 FALSE了,非常的好用,下面我深入來為各位介紹in_array() 函數.
最近在用php寫一段代碼時,要用到判斷某值是否在另外一組值中。而in_array 函數就是用來檢查數組中是否存在某個值 。直接通過概念理解比較模糊,可以通過具體例子了解其作用。
語法如下:
bool in_array( mixed needle, array array [, bool strict] )
參數說明:
<?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[] 。
希望本文所述對大家的php程序設計有所幫助。