警告:不能将标量值用作数组

时间:2016-02-05 07:48:07

标签: php

我有一个非常基本的代码。它涉及会话和数组。

$abc=array();
$abc['name']=$db_name; //When i echo this one.It does echo the name i.e. 'Tilak'
$_SESSION['userpasswordmatch']=true;
$_SESSION['userpasswordmatch']['name']=$abc['name'];
echo $_SESSION['userpasswordmatch']['name'];

现在当我尝试运行代码时。它向我显示一条警告,指出不能使用标量值作为数组以及上面代码中的echo部分不显示任何内容

问题:

1)为什么我会看到此错误以及解决此问题的方法是什么?

2)如何回应上述会议。

注意:

1) $ db_name 是我从数据库获取的用户名。它工作正常,我在 $ db_name 中得到正确的值。

更新

即使我这样做也会发生同样的事情:

 $_SESSION['userpasswordmatch']=true;
 $_SESSION['userpasswordmatch']['name']=$db_name;
 echo $_SESSION['userpasswordmatch']['name'];

1 个答案:

答案 0 :(得分:2)

首先,您要定义$_SESSION['userpasswordmatch']=true;true是标量值。然后$_SESSION['userpasswordmatch']['name']=$db_name;$_SESSION['userpasswordmatch']视为array

您只需$_SESSION['userpasswordmatch']['name']=$db_name;echo即可。

无需将其设置为true。这可行 -

$abc=array();
$abc['name']=$db_name; //When i echo this one.It does echo the name i.e. 'Tilak'
$_SESSION['userpasswordmatch']['name']=$abc['name'];
echo $_SESSION['userpasswordmatch']['name'];

<强>更新

无需定义空白array。当您设置$_SESSION['userpasswordmatch']['name'] = $db_name;时,$_SESSION['userpasswordmatch']已定义为array

$_SESSION['userpasswordmatch']['check']= true; // use this for that check