2015-10-06 284 views
1

我想檢查給定值是否存在於數組中。 這裏我有一個函數,我將傳遞一個值作爲參數。 我有一個陣列$_SESSION['cart']在那裏我已經存儲了多個值,而迭代陣列我想檢查的product_id是在陣列如何檢查數組中是否存在給定值

我打電話功能的同時遍歷數組檢查的product_id存在

<?php 
     foreach($_SESSION['cart'] as $item): 
     getCartitems($item); 
     endforeach; 
    ?> 

功能

function productIncart($product_id){ 
     //check if the $_SESSION['cart']; has the given product id 
     //if yes 
     //return true 
     //else 
     //return false 
} 

我該怎麼做?

+0

你的數據是如何在$ _SESSION ['cart']'中構造的? – vitozev

回答

1

試試這個

function productIncart($product_id){ 
    if (in_array($product_id, $_SESSION['cart'])) 
    { 
    return true; 
    } 
    else 
    { 
    return false"; 
    } 
} 
2

你可以看到,如果一個數組的給定鍵使用isset功能設置。

<?php 
$array = array("foo" => "bar"); 

if(isset($array["foo"])) 
{ 
echo $array["foo"]; // Outputs bar 
} 

if(isset($array["orange"])) 
{ 
echo $array["orange"]; 
} else { 
echo "Oranges does not exist in this array!"; 
} 

要檢查的給定值是在陣列中,可以使用的in_array功能。

if (in_array($product_id, $_SESSION["cart"])) 
    { 
    return true; 
    } 
    else 
    { 
    return false"; 
    } 
+0

爲什麼不只是'返回in_array($ product_id,$ _SESSION [「cart」])'? 'if(bool){return true; } else {return false; }'是寫'return bool;'的一個很長的路。 – Anders

+0

爲什麼還要回呢?爲什麼不直接做一個簡寫?爲什麼即使在探測器設計的一塊軟件中檢查陣列,你也不會懷疑陣列中有什麼。從學習的角度來看,這使得更多的感覺:)但點了。不要在Stackoverflow上成爲教師! :d –

2

in_array返回true如果該項目是存在於陣列別的false英寸你可以試試這個 -

function productIncart($product_id){ 
    return in_array($product_id, $_SESSION['cart']); 
}