Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write long IF more prettier?

Tags:

php

I have long IF:

if(rand(1, 100) == 22 && $smth < time() && 
$smths > 5 && $sxsxsx > 250 && 
!$_SESSION['false'])
{
    echo "wow, big if just happened!";
}

How to write it more "prettier"?

like image 343
good_evening Avatar asked Nov 28 '22 04:11

good_evening


2 Answers

I prefer breaking before the boolean operators.

if(rand(1, 100) == 22
   && $smth < time()
   && $smths > 5
   && $sxsxsx > 250
   && !$_SESSION['false']
)
like image 174
Ignacio Vazquez-Abrams Avatar answered Dec 13 '22 09:12

Ignacio Vazquez-Abrams


I like to name my conditions and group them so its clear what their purpose is.

$is22 = rand(1, 100) == 22;
$someTime = $smth < time() && $smths > 5;
$meetsSx = $sxsxsx > 250;
$inSession = !$_SESSION['false'];
if ($is22 && $someTime && $meetsSx && $inSession) {
     // do something
}
like image 32
Daniel A. White Avatar answered Dec 13 '22 11:12

Daniel A. White