如何检查数组中是否存在给定值
我想检查给定值是否存在于数组中。 这里我有一个函数,我将传递一个值作为参数。 我有一个阵列$_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
}
我该怎么做?
试试这个
function productIncart($product_id){
if (in_array($product_id, $_SESSION['cart']))
{
return true;
}
else
{
return false";
}
}
你可以看到,如果一个数组的给定键使用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";
}
为什么不只是'返回in_array($ product_id,$ _SESSION [“cart”])'? 'if(bool){return true; } else {return false; }'是写'return bool;'的一个很长的路。 – Anders
为什么还要回呢?为什么不直接做一个简写?为什么即使在探测器设计的一块软件中检查阵列,你也不会怀疑阵列中有什么。从学习的角度来看,这使得更多的感觉:)但点了。不要在Stackoverflow上成为教师! :d –
in_array
返回true
如果该项目是存在于阵列别的false
英寸你可以试试这个 -
function productIncart($product_id){
return in_array($product_id, $_SESSION['cart']);
}
你的数据是如何在$ _SESSION ['cart']'中构造的? – vitozev