Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using '&&' inside foreach?

I am looking for smart solution, maybe you could help me out. Currently I am doing an own Authentication (Separate Class) system for my Webshop project. My problem is, that I need conditional statement inside foreach loop, to return the code (see below).
Any suggestions?

My code currently look like this

public function regiAuth($email, $password, $firstname, $lastname)
{
    $authContainer = [$email, $password, $firstname, $lastname];
    foreach ($authContainer as $a) {
        return !empty($_POST[$a]);
    }
}

And I want to result this (With &&)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

return !empty($_POST[$email]) && !empty($_POST[$password]) &&
!empty($_POST[$firstname]) && !empty($_POST[$lastname])

>Solution :

I believe you could do simply by do

foreach ($authContainer as $a) {
  if (empty($_POST[$a])
    return false;
}
return true;

instead of checking if all of them are full, you look if there is at least one empty.

it is a good practice to stop iteration if you find one element that is not as expected, imagine if you had an array of hundreads of assertions to do.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading