Home > Blockchain >  How to declare an empty variable inside function in PHP
How to declare an empty variable inside function in PHP

Time:01-31

It sound a Stupid question but I don know what is the problem each time i try to declare a variable inside a function it gives me an error !

function emptyInputSignup($name, $email, $password, $confirm_password)
{

    $result;

    if (empty($name) || empty($email) || empty($password) || ($confirm_password)) {
        $result = true;
    } else {
        $result = false;
    }
    return $result;
}

I've tried to declare it and i got an error.

CodePudding user response:

You don't declare variables in PHP, you define them.

There's no need for $result; and it actually means "read the value of the variable $result and then do nothing with it" - which will give you an undefined variable error if $result isn't defined (which, in your case, it is).

What you have to do instead is initialize $result to some value, or leave it out completely:

$result = false;

For example.


Your code can be greatly simplified by just using assigment:

$result = empty($name) || empty($email) || empty($password) || ($confirm_password);

No need for the if. And you can actually ditch the $result variable entirely:

function emptyInputSignup($name, $email, $password, $confirm_password) {
    return empty($name) || empty($email) || empty($password) || ($confirm_password);
}

CodePudding user response:

You can initialize a variable like this:

$result = NULL;

You can try using any of the following:

{
    $result = false;
    if (empty($name) || empty($email) || empty($password) || ($confirm_password)) {
        $result = true;
    }
    return $result;
}
// or
{
    if (empty($name) || empty($email) || empty($password) || ($confirm_password)) {
       return true;
    }
    return false;
}
// or
{
    return (empty($name) || empty($email) || empty($password) || ($confirm_password));
}

All these constructs produce the same result.

  •  Tags:  
  • php
  • Related