PHP in_array函數檢查數組中是否存在某個值

來源:互聯網
上載者:User

最近在用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[] 。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.