Is there any simpler format for the following if
statement below?
if((!empty($_SESSION['email'])) && (!empty($_SESSION['serial'])) && (!empty($_SESSION['name'])) && (!empty($_SESSION['number'])) && (!empty($_SESSION['institution'])) && (!empty($_SESSION['address'])) && (!empty($_SESSION['item2']))){
echo "OK u can proceed";
} else {
echo "U didn't complete the requested info";
}
Sorry if this is too simple for you, but really appreciate any pro suggestion.
Because conditional statement will "short circuit" on the first failure, re-writing your process using an iterator will be less performant.
If you only want to provide generalized feedback to the user, use your current method without the surplus parentheticals.
if(!empty($_SESSION['email']) &&
!empty($_SESSION['serial']) &&
!empty($_SESSION['name']) &&
!empty($_SESSION['number']) &&
!empty($_SESSION['institution']) &&
!empty($_SESSION['address']) &&
!empty($_SESSION['item2'])){
// valid
}
Alternatively (same same):
if(empty($_SESSION['email']) ||
empty($_SESSION['serial']) ||
empty($_SESSION['name']) ||
empty($_SESSION['number']) |
empty($_SESSION['institution']) ||
empty($_SESSION['address']) ||
empty($_SESSION['item2'])){
// invalid
}
Only if you wish to specify the cause of the invalidation should you bother to set up an iterative process. Furthermore, if you are going to perform iterations to validate, you can take the opportunity to remove any unwanted elements from the $_SESSION
array that evil-doers may have injected to take advantage of any future loops on the superglobal.
$valid_keys=['email','serial','name','number','institution','address','item2'];
$validated=true; // default value
foreach($valid_keys as $key){
if(!empty($_SESSION[$key])){
$session_data[$key]=$_SESSION[$key];
}else{
echo "Oops, there was missing data on $key";
$validated=false;
break;
}
}
if($validated){...
// from this point, you can confidently run loops on `$session_data` or slap it directly into a pdo call knowing that it has been validated and ordered.
All that said, if there is even the slightest chance that your $_SESSION
elements could hold zero-ish/false-y/empty values, then isset() is the better call (only NULL
will get caught). Another good thing about isset()
is that it allows multiple variables to be written into the single call and maintains the same/intended performance.
if(isset($_SESSION['email'],$_SESSION['serial'],$_SESSION['name'],$_SESSION['number'],$_SESSION['institution'],$_SESSION['address'],$_SESSION['item2'])){
// valid
}
or
if(!isset($_SESSION['email'],$_SESSION['serial'],$_SESSION['name'],$_SESSION['number'],$_SESSION['institution'],$_SESSION['address'],$_SESSION['item2'])){
// invalid
}