[英]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
空物清單:
碼
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']);
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.