Variable validation

Asked

Viewed 72 times

-6

I saw some examples of variable checking to set values.

For example:

$nome ?? "Tem nome";
$nome or "Tem nome";

In this case, you have the reverse validation?

I’d like to do something like that:

if(!$nome) ? "Não tem nome";
  • 1

    You could explain better, because the way you explained it is exactly what the condition is already doing. When you use $nome ?? "Tem nome" you are saying that if there is any value in the variable you will use it, if you do not use the other as default.

1 answer

1


The question does not say what you want to get as a result. The first line of code will get the text if the variable does not exist or has a null value and it only makes sense to use it as part of a larger expression, usually to store the result in the variable itself being evaluated. The second line does not get the text as a result, so they are not equivalent, it results in 0 or 1, the question there is only to determine whether the second operand of the or will be evaluated or not, but evaluating is different from taking this value as a result, in which case the result in such cases will always be 1.

The third code you want to do makes no sense because it seems you want if you have nothing to keep and if you have something to change the content. This is not even a validation. But I could do it like this:

Use the conditional operator normal:

$nome ? $nome : "Não tem nome"

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.