foreach声明没有检查所有条件

I'm new to PHP. I'm trying to check that no field is empty in a certain form, so I used a foreach statement but it only checks one by one instead of all at once.

Here is my code:

<?php

if (isset($_POST[submit])) {
    ValidateUser();
}

function ValidateUser() {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $details = array($username, $password);

    foreach($details as $detail) {
        if (!empty($detail)) {
            echo "hurrayy";
        }
    }
}

?>

So instead of displaying "hurrayy" when BOTH username and password are not empty, it displays as long as one of them is not empty. Please help.

You don't need to assign them to an array and loop

function ValidateUser() {
    if(!empty($_POST['username']) AND !empty($_POST['password'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    echo "Hurray!";
    }
}

8 lines down to 5, no loop and no array assignment.

Add a break after the message has been echo'ed once. It will stop the foreach loop.

foreach($details as $detail) {
    if (!empty($detail)) {
        echo "hurrayy";
        break;
    }
}

So you want to display "hurrayy" only if none of the fields in the array are empty? You need to check them all first and then decide.

function ValidateUser() {
  $username = $_POST['username'];
  $password = $_POST['password'];
  $details = array($username, $password);

  $empty_field = false;

  foreach($details as $detail) {
    if (empty($detail)) {
        $empty_field = true;
    }
  }

  if (!$empty_field)
    echo "hurrayy";
}

yes it will enter the if statement because $username and $password is considered as value in the array even if those two doesn't have a value.