[英]PHP in_array if only item
我正在使用in_array來檢測值是否在PHP數組中,我的數組看起來像這樣...
$fruits = array("banana", "grape", "orange", "apple");
/* is grape in the array */
if (in_array('grape', $fruits)) {
echo 'Grape Detected';
} else {
echo 'Grape not detected';
}
我正在嘗試對此進行修改,以便它也可以檢測到“葡萄”何時是數組中的唯一項,因此,如果數組看起來像這樣……
$fruits = array("grape", "grape", "grape");
要么...
$fruits = array("grape");
然后,我可以顯示一條自定義消息,有人可以看到示例嗎?
檢查是否有不止一個元素,並且是否符合您的條件。
if(count($fruits) === 1 && in_array('grape', $fruits)) {
echo "There's only one fruit here, and it's a grape!";
}
編輯:
您可以檢查“ grape”是否是數組中唯一的東西,以及通過這種方式有多少個葡萄:
$condition_met = false;
foreach ($fruits as &$iterator) {
if($iterator !== 'grape') {
$condition_met = true;
}
}
if($condition_met === false)
{
echo 'There are only grapes in this fruits basket! There are ' . count($fruits) . ' unique beauties!';
}
要僅在列表中只有“ grape”(水果)時顯示自定義消息,可以通過將代碼更改為:
/* is grape in the array */
if (in_array('grape', $fruits)) {
if (count(array_unique($fruits)) === 1) {
echo 'Grape is the only fruit in the list';
} else {
echo 'Grape detected';
}
} else {
echo 'Grape not detected';
}
這是最簡單的方法:
if (array_unique($fruits) === array('grape')) {
echo 'Grape Detected';
}
說明: array_unique
從數組中刪除所有重復的值。 如果“ grape”是數組中的唯一項,則array_unique($fruits)
的結果應等於array('grape')
。 ===
運算符檢查兩個值都是數組,並且它們都具有相同的元素。
嘗試這個,
使用array_count_values內置函數。
<?php
$fruits = array("banana", "grape", "orange", "apple","grape", "grape", "grape");
$tmp_fruits = array_count_values($fruits);
/* is grape in the array */
foreach($tmp_fruits as $fruit=>$total){
echo $fruit." Detected ".$total." Times."."<br />";
}
?>
您可以使用函數array_count_values()
。 這將返回一個新數組,其中包含重復項的次數。
<?php
$fruits = array("grape", "grape", "grapr");
$vals = array_count_values($fruits);
echo 'Unique Items: '.count($vals).'<br><br>';
print_r($vals);
?>
將輸出:
Unique Items: 2
Array ( [grape] => 2 [grapr] => 1 ) //Shows the item in the array and how many times it was repeated
然后,您可以遍歷新數組$vals
,以找出重復某項的次數並顯示相應的消息。
希望它可以幫助您。
如果滿足以下條件,則此檢查為真:
$uniqueFruits = array_unique($fruit); if (count($uniqueFruits) == 1 && $uniqueFruits[0] == 'grape') { // Only 'grape' in here } elseif() { // Some other check } else { // Otherwise }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.