Awais Ahmad Awais Ahmad - 1 month ago 11
PHP Question

how to compare array for single result using if statement

i was doing validation for user form after each validation i used to store "valid" in a array index and at last comparing them like this:

if(isset($fullname)){
if ($valid["name"]=="valid"&&$valid["username"]=="valid"&&$valid["password"]=="valid"&&$valid["email"]=="valid") {
session_start();
$_SESSION["reg_name"] = $fullname1;
$_SESSION["reg_username"] = $username1;
$_SESSION["reg_email"] = $email1;
$_SESSION["reg_password"] = $password1;
$_SESSION["reg_gender"] = $_REQUEST['gender'];
header("location:validation&insertion.php");
}


Well i will check validation and then make session .

My question is there any short way to check the whole array across a single value like "valid"?
I hope you have understand my question.Comment it if it is not asked well.
Do not rate as negative.Please ignore my grammar mistakes.I hate those who edit my question's grammar.

Answer

You can just count the number of unique values and check if it's equal to 1, then check one value if it is "valid".

if (count(array_unique($valid)) === 1 && $valid["name"] === "valid") {
    session_start();
    $_SESSION["reg_name"] = $fullname1;
    $_SESSION["reg_username"] = $username1;
    $_SESSION["reg_email"] = $email1;
    $_SESSION["reg_password"] = $password1;
    $_SESSION["reg_gender"] = $_REQUEST['gender'];
    header("location:validation&insertion.php");
}

Or just simply check if a "notvalid" value is found in the array:

if (!in_array("notvalid", $valid)) {
    session_start();
    $_SESSION["reg_name"] = $fullname1;
    $_SESSION["reg_username"] = $username1;
    $_SESSION["reg_email"] = $email1;
    $_SESSION["reg_password"] = $password1;
    $_SESSION["reg_gender"] = $_REQUEST['gender'];
    header("location:validation&insertion.php");
}