Asked  7 Months ago    Answers:  5   Viewed   37 times

I want to check if:

  • a field in the array isset
  • the field === true

Is it possible to check this with one if statement?

Checking if === would do the trick but a PHP notice is thrown. Do I really have to check if the field is set and then if it is true?

 Answers

59

If you want it in a single statement:

if (isset($var) && ($var === true)) { ... }

If you want it in a single condition:

Well, you could ignore the notice (aka remove it from display using the error_reporting() function).

Or you could suppress it with the evil @ character:

if (@$var === true) { ... }

This solution is NOT RECOMMENDED

Wednesday, March 31, 2021
 
turik
answered 7 Months ago
75

Just try with:

if ( in_array($_GET['id'], array(1, 3, 4, 5)) ) {}
Wednesday, March 31, 2021
 
Anele
answered 7 Months ago
55

In a condition like if (p || q || r), the whole if statement evaluates to true if at least one of the three conditions is true. If you don't have MANAGEMENT role, then !in_array('MANAGEMENT',$_SESSION['roles']) will be true, hence access will be denied.

I would recommend you to invert the if statement, so that if true, the access is granted, otherwise it's denied. So:

if (in_array('ADMIN', $_SESSION['roles']) || in_array('MANAGEMENT', $_SESSION['roles']) || $requester == $_SESSION['tnumber'] ) {
    // allowed
} else {
    // denied
}

It will also help the readability of your code if you extract the big condition to a separate function.

Wednesday, March 31, 2021
 
Semirix
answered 7 Months ago
44

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

Therefore

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}
Thursday, July 8, 2021
 
akohout
answered 4 Months ago
67

Do you expect temp.MOD file to be in the current directory (the directory from which you run your application), or you want it to be in the "directory" folder? In the latter case, try creating the file this way:

boolean check = new File(directory, temp).exists();

Also check for the file permissions, because it will fail on permission errors as well. Case sensitivily might also be the cause of the issue as Spaeth mentioned.

Friday, August 13, 2021
 
Matt Bullock
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :