rewriting if statement in PHP
I have this conditio开发者_高级运维nal if statement:
if ( isset($_POST['x']) && empty($_POST['x']) && isset($_SESSION['x']) && $_SESSION['x'] )
$response['x'] = 1;
else
$response['x'] = 2;
I want to make it something like the opposite, for example:
if ( !isset($_POST['iQapTcha']) || !empty($_POST['iQapTcha']) || !isset($_SESSION['iQaptcha']) || !$_SESSION['iQaptcha'] )
$response['captcha'] = 2;
exit();
Is my new version correct? or this is not the best idea?
Thanks.
Simpliest way:
if (!(*old condition here*))
I guess whether or not it's correct depends on what you want to do.
If you have a condition that you just want to negate, you can wrap everything in !()
:
if( a == b && c == d ) ...
// the negation is:
if( !( a == b && c == d ) ) ...
Additional comment: ( !isset( $x ) || !empty( $x ) ) == !empty( $x )
so your second statement can be shortened to
if( !empty($_POST['iQapTcha']) || !empty( $_SESSION['iQaptcha'] ) ) ...
Yes, totally correct, and probably the best option An alternative would be
if !( isset($_POST['x']) && empty($_POST['x']) && isset($_SESSION['x']) && $_SESSION['x'] )
but it's not as good as PHP will have to evaluate all the variables. With your option, it can stop when one of the condition is met (since it's OR)
精彩评论