簡體   English   中英

PHP - 將IF語句放入變量中

[英]PHP - Placing an IF statement into a variable

我想在變量中放置一個if語句以減少代碼行...例如我想這樣做:

$empty = if(empty($_POST['username']) && empty($_POST['password']))
if($empty){ // echo message; 
}
elseif(!$empty){ ///echo message; 
}

可以生產類似上面的東西嗎? 還是我把事情弄得太復雜了?

只需省略if:

$empty = empty($_POST['username']) && empty($_POST['password']);

您可以使用三元運算符

$message = ( empty($_POST['username']) && empty($_POST['password']) ) ? 'empty': 'not empty';
echo $message;

嘗試這個

$empty = (empty($_POST['username']) && empty($_POST['password'])) ? 0 : 1;

if($empty){ // Not empty message here...; 

}
else{ ///Empty message here....; 

}

使用三元運算符:

echo empty($_POST['username']) && empty($_POST['password']) ? 'empty message' : 'Not empty message';

您可以直接使用echo和ternary運算符,而不是獲取$empty值並將其打印出來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM