Statements with boolean expressions

Statements with many expressions can become hard to read and look complicated. For example:

if (strtolower($imageExtension == 'jpg' || strtolower($imageExtension) == 'jpeg' || strtolower($imageExtension) == 'gif' || strtolower($imageExtension) == 'png') { //some code that does something }

As you can see the above code is a little messy. But what happens if we need to add a couple more conditions such as:

if (strtolower($imageExtension) == 'jpg' || strtolower($imageExtension) == 'jpeg' || strtolower($imageExtension) == 'gif' || strtolower($imageExtension) == 'png' || $imageApproved || (isset($_SESSION['admin']) && $_SESSION['admin'] > 10)) { //some code that does something }

Our code is getting messier and messier and more complicated than it needs to be. One way to fix the problem is to use boolean statements:

$jpeg = strtolower($imageExtension) == 'jpg' || strtolower($imageExtension) == 'jpeg'; $gif = strtolower($imageExtension) == 'gif'; $png = strtolower($imageExtension) == 'png'; $adminApproved = isset($_SESSION['admin']) && $_SESSION['admin'] > 10; if ($jpeg || $gif || $png || $imageApproved || $adminApproved) { //some code that does something }

Our code looks much cleaner and should be easier to read. If you have three or more conditions in your if statements then it is likely that it is hard to read. Therefore you can use boolean statements to make your code more readable.