繁体   English   中英

PHP检查数组是否为空逻辑不起作用

[英]PHP Checking if Array is empty logic not working

我有一个页面加载并创建一个空数组:

$_SESSION['selectedItemIDs'] = array();

如果用户尚未添加存储在数组中的任何选择,则应检查数组并进行相应的分支,但是我的logic/syntax似乎有一些错误,导致此处失败。

这是我测试$_SESSION['selectedItemIDs']是否设置为空的地方:

if (isset($_SESSION['selectedItemIDs']) && $_SESSION['selectedItemIDs'] !== '') {
    // update the selections in a database
} else {
    // nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}

如果不打印选择内容进行测试,如果我打印$_SESSION['selectedItemIDs']数组,则会得到以下信息:

[selectedItemIDs] => Array
    (
    )

但是,没有设置$selectedItems变量-当我期望它为false时,它将if测试评估为true,但显然我在这里误解了一些东西。

使用empty()函数。

empty() -如果变量为空字符串,false,array(),NULL,“ 0?”,0和未设置的变量,则它将返回true。

句法

empty(var_name)

返回值

FALSE if var_name has a non-empty and non-zero value.

值类型 :

Boolean

空物清单:

  • “ 0”(0作为字符串)
  • 0(0为整数)
  • “”(空字符串)
  • 空值
  • “”(空字符串)
  • array()(一个空数组)
  • $ var_name; (已声明变量但类中没有值)

if (!empty($_SESSION['selectedItemIDs']) ) {
    // update the selections in a database
} else {
    // nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}
$_SESSION['selectedItemIDs'] = array();

此变量已设置,但为空。 isset($_SESSION['selectedItemIDs'])检查变量是否存在,即使变量不存在也是如此。

要检查是否有任何东西,只需使用

empty($_SESSION['selectedItemIDs']);

PHP DOC-空

if (!empty($_SESSION['selectedItemIDs'])) {
    // update the selections in a database
} else {
    // nothing selection so just record this in a variable
    $selectedItems = 'no selected items were made';
}

isset($_SESSION['selectedItemIDs']) =>它将检查是否设置了此参数。

$_SESSION['selectedItemIDs'] !== '' =>这将完全比较您的参数类型不是”,但在这里我猜您的selectedItemIDs是数组,因此它可以让您进入

您可以检查此数组的计数。

if (isset($_SESSION['selectedItemIDs']) && count($_SESSION['selectedItemIDs']) > 0) {
    // update the selections in a database
} else {
    // nothing selection so just record this in a variable
$selectedItems = 'no selected items were made';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM