[英]How can I add new items to my session array if value is not already in it? PHP
I am trying to add new items to my array if they don't already exist but below code shows me an error: 我正在尝试将尚不存在的新项目添加到我的数组中,但是下面的代码显示了一个错误:
// Check if session exists
if(!isset($_SESSION['coupon'])){
// Create array from session
$_SESSION['coupon']['couponcode'] = array();
}
if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
// Add couponcode to session if it does not already exist
$_SESSION['coupon']['couponcode'][] = $coupon;
}
$_SESSION['coupon']['couponcode'][] = $coupon;
Gives: PHP Fatal error: Uncaught Error: [] operator not supported for strings
提供:
PHP Fatal error: Uncaught Error: [] operator not supported for strings
But I thought this was the way to add to the array, if I remove the brackets it just replaces the value everytime. 但是我认为这是添加到数组的方法,如果我删除括号,它将每次都替换该值。
I have session_start();
我有
session_start();
everywhere at the top of my pages. 我页面顶部的所有位置。
You can use array_push(): 您可以使用array_push():
if(empty($_SESSION['coupon'])){
// Create array from session
$_SESSION['coupon']['couponcode'] = array();
}
else
{
if(!in_array( $coupon,$_SESSION['coupon']['couponcode'])) //check in array available
{
array_push($_SESSION['coupon']['couponcode'], $coupon); //push to array
}
}
First of all,do not put blindly session_start() on top of every page. 首先,不要盲目地将session_start()放在每个页面的顶部。 It will start session again even if a previous session was running and will refresh your all values, so first thing, change that to:
即使先前的会话正在运行,它也会再次开始会话,并将刷新您的所有值,因此,第一件事,请将其更改为:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
this way it starts the session only if it doesn't exist. 这样,仅当会话不存在时才启动会话。
Now, you are getting error because somehow your $_SESSION['coupon']['couponcode']
is a string so add an additional check: 现在,您因为遇到了问题,因为您的
$_SESSION['coupon']['couponcode']
是一个字符串,因此请添加其他检查:
if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
// Add couponcode to session if it does not already exist
if (empty($_SESSION['coupon']['couponcode']) || !is_array($_SESSION['coupon']['couponcode']))) {
$_SESSION['coupon']['couponcode'] = [];
}
$_SESSION['coupon']['couponcode'][] = $coupon;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.