Of the following, which conditional statement is best practice:
if ($_GET['type'] == 'user' || $_GET['type'] == 'salesmen')
or
if ($_GET['type'] == ('user' || 'salesmen'))
Thanks for your help.
Of the following, which conditional statement is best practice:
if ($_GET['type'] == 'user' || $_GET['type'] == 'salesmen')
or
if ($_GET['type'] == ('user' || 'salesmen'))
Thanks for your help.
Always use the first one:
if ($_GET['type'] == 'user' || $_GET['type'] == 'salesmen')
The second one is a valid PHP ststement but it will produce unexpected results ( Not the output you are expecting ).
Have you tried it? One simple try would point you that the second part will not work as you expected.
However, I would suggest in_array()
if (in_array($_GET['type'], array('user', 'salesmen'))) {
//
}
or
$type = array('user', 'salesmen');
if (in_array($_GET['type'], $type)) {
//
}
The first one is correct. In the second one you are actually comparing $_GET['type']
with a boolean expression ('user' || 'salesmen'
)
In your second example
('user' || 'salesmen')
Will be evaluated first, which results in a boolean true. Resulting in the following expression to be evaluated for the first:
$_GET['type'] == true
Which may or may not be true. In this case that would be true if $_GET['type'] is 1, true, an object, a string, or anything else that evaluates to true. This aspect is hidden in your question, but I would like to highlight that it could be prevented by using the identity operator (===).
Even prettier (imho):
$typeIsUser = $_GET['type'] === 'user';
$typeIsSalesMan = $_GET['type'] === 'salesmen';
if ($typeIsUser || $typeIsSalesmen){
...
}
Or use in_array! The possibilities are endless.
The first option is the valid one, the second one is not doing what you think it is.
You can find a full discussion of the various options to achieve this here:
The first thing you will want to do is make sure the parameter exists, otherwise you may see notices about a missing array index with a URL like /page?foo=bar
:
if (isset($_GET['type'])) { ... }
Combining that with the rest of your code:
if (isset($_GET['type']) && ($_GET['type'] == 'user' || $_GET['type'] == 'salesmen')) { ... }
Alternatively:
if (isset($_GET['type']) && in_array($_GET['type'], ['user', 'salesmen'])) { ... }
This code:
if ($_GET['type'] == ('user' || 'salesmen'))
Compares $_GET['type']
with true
, yielding true
for most values.