Reputation:
i am trying to check whther $_GET['id'] is set and is numeric else killing the code execution.,
following both codes are working for me , but would like to know whats the difference in between them ?
php condition 1
<?php
if(!isset($_GET['id']) || (isset($_GET['id']) && !is_numeric($_GET['id']))) {
die();
}
php condition 2
<?php
if(!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die();
}
Upvotes: 1
Views: 77
Reputation: 248
In the first one It makes three checks which are unnecessary. In the second it won't catch one of the conditions required
|| means OR - either one of the conditions should evaluate to true
&& means AND - both conditions must be true
To work properly you need this
if (!isset($_GET['id']) && !is_numeric[$_GET['id']])
die();
The first statement does the same thing but it check if $_GET['id'] is set two times which isn't needed.
Upvotes: -4
Reputation: 175007
You're basically doing
A || (!A && B)
if A
is true
, then the rest won't be executed.
If A
is false, !A
will be true anyway. So the !A
is redundant.
Functionally they are the same, but in practice, you don't need the extra condition.
You can see the logical explanation here:
Upvotes: 3
Reputation: 1064
The difference is that the first one has an unnecessary extra check if $_GET['id']
is set. PHP uses what is called short-circuit boolean evaluation, which means that if the left side of an ||
is true, the right side doesn't need to be evaluated. So, even in the second example, !is_numeric($_GET['id'])
will never get evaluated unless isset($_GET['id'])
is true.
Logically these statements are equivalent.
Upvotes: 5