簡體   English   中英

如何檢查數組是否包含 php 中的特定值?

[英]How can I check if an array contains a specific value in php?

我有一個 Array 類型的 PHP 變量,我想知道它是否包含特定值並讓用戶知道它在那里。 這是我的數組:

Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room) 

我想做類似的事情:

if(Array contains 'kitchen') {echo 'this array contains kitchen';}

執行上述操作的最佳方法是什么?

使用in_array()函數

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}
// Once upon a time there was a farmer

// He had multiple haystacks
$haystackOne = range(1, 10);
$haystackTwo = range(11, 20);
$haystackThree = range(21, 30);

// In one of these haystacks he lost a needle
$needle = rand(1, 30);

// He wanted to know in what haystack his needle was
// And so he programmed...
if (in_array($needle, $haystackOne)) {
    echo "The needle is in haystack one";
} elseif (in_array($needle, $haystackTwo)) {
    echo "The needle is in haystack two";
} elseif (in_array($needle, $haystackThree)) {
    echo "The needle is in haystack three";
}

// The farmer now knew where to find his needle
// And he lived happily ever after

in_array

<?php
    $arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");    
    if (in_array("kitchen", $arr))
    {
        echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
    }
?>

您需要在陣列上使用搜索算法。 這取決於您的陣列有多大,您可以選擇哪種使用方式。 或者,您可以使用以下內置函數:

http://www.w3schools.com/php/php_ref_array.asp

http://php.net/manual/zh/function.array-search.php

來自http://php.net/manual/en/function.in-array.php

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

除非設置嚴格,否則使用松散比較在干草堆中搜索針。

if (in_array('kitchen', $rooms) ...

使用動態變量在數組中搜索

 /* https://ideone.com/Pfb0Ou */

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

/* variable search */
$search = 'living_room';

if (in_array($search, $array)) {
    echo "this array contains $search";
} else
    echo "this array NOT contains $search";

以下是如何執行此操作:

<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

請確保您搜索的廚房廚房沒有。 此功能區分大小寫。 因此,以下功能根本無法使用:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

如果您想要一種快速的方法來使此搜索不區分大小寫 ,請在此回復中查看建議的解決方案: https : //stackoverflow.com/a/30555568/8661779

資料來源: http//dwellupper.io/post/50/understanding-php-in-array-function-with-examples

$your_array=Array ( [0] => 廚房 [1] =>卧室 [2] =>living_room [3] =>dining_room); if(in_array('kitchen', $your_array)) {echo '這個數組包含廚房';}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM