user1642018
user1642018

Reputation:

Whats the difference in these two php conditions?

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

Answers (3)

ehwas
ehwas

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

Madara&#39;s Ghost
Madara&#39;s Ghost

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:

Logic

Upvotes: 3

Roel Harbers
Roel Harbers

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

Related Questions