Php 如何检查数组中是否存在给定值
我想检查数组中是否存在给定的值。 这里我有一个函数,其中我将传递一个值作为参数。 我有一个数组Php 如何检查数组中是否存在给定值,php,arrays,Php,Arrays,我想检查数组中是否存在给定的值。 这里我有一个函数,其中我将传递一个值作为参数。 我有一个数组$\u SESSION['cart'],在这里我存储了多个值,在迭代数组时,我想检查产品id是否在数组中 我在迭代数组以检查产品标识是否存在时调用函数 <?php foreach($_SESSION['cart'] as $item): getCartitems($item); endforeach; ?> 我该怎么做呢
$\u SESSION['cart']
,在这里我存储了多个值,在迭代数组时,我想检查产品id是否在数组中
我在迭代数组以检查产品标识是否存在时调用函数
<?php
foreach($_SESSION['cart'] as $item):
getCartitems($item);
endforeach;
?>
我该怎么做呢?试试这个
function productIncart($product_id){
if (in_array($product_id, $_SESSION['cart']))
{
return true;
}
else
{
return false";
}
}
试试这个
function productIncart($product_id){
if (in_array($product_id, $_SESSION['cart']))
{
return true;
}
else
{
return false";
}
}
您可以看到是否使用函数设置了数组的给定键
<?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!";
}
if (in_array($product_id, $_SESSION["cart"]))
{
return true;
}
else
{
return false";
}
您可以看到是否使用函数设置了数组的给定键
<?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!";
}
if (in_array($product_id, $_SESSION["cart"]))
{
return true;
}
else
{
return false";
}
in_array
如果数组中存在项,则返回true
,否则返回false
。你可以试试这个-
function productIncart($product_id){
return in_array($product_id, $_SESSION['cart']);
}
in_array
如果数组中存在项,则返回true
,否则返回false
。你可以试试这个-
function productIncart($product_id){
return in_array($product_id, $_SESSION['cart']);
}
您的数据在
$\u会话['cart']
中是如何构造的?您的数据在$\u会话['cart']
中是如何构造的?为什么不在数组中返回($product\u id,$\u会话['cart'])if(bool){return true;}else{return false;}
只是编写return bool的一个很长的过程代码>。为什么还要返回它?为什么不做个速记呢?为什么要在prober设计的软件中检查阵列,您对阵列中的内容没有疑问。从学习的角度来看,这更有意义:)但这一点是正确的。不要对Stackoverflow进行教学!:为什么不仅仅是以数组形式返回($product\u id,$\u SESSION[“cart”])
if(bool){return true;}else{return false;}
只是编写return bool的一个很长的过程代码>。为什么还要返回它?为什么不做个速记呢?为什么要在prober设计的软件中检查阵列,您对阵列中的内容没有疑问。从学习的角度来看,这更有意义:)但这一点是正确的。不要对Stackoverflow进行教学!:D