From a form I send a value field , and I want to process said field as long as it is not empty and does not exceed the length of 15 characters. I did this, but it still shows PROCESS .
if (strlen(!empty($_POST['valor'])) <= 15) {
echo "PROCESAR";
}
You need two separate conditions. You can't do it all together like you have it. As explained in a comment. The condition
!empty($_POST['valor'])
will always evaluate totrue
orfalse
. When you evaluate the second condition, it's always going to bestrlen(true)
orstrlen(false)
, and those two values are going to evaluate to true because they're both less than 15. The correct form would look like this:Your problem
First, and before jumping to give an answer, I'm going to explain why your code doesn't work.
According to the documentation it
empty()
will return a boolean andstrlen()
it will return an integer, this means that if we doeither
It will return 0 and 1 respectively, as we know 1 and 0 are less than or equal to 15 so your condition no matter what happens will always be true.
Response
On the other hand, what none of the answers do not take into account is that if it
$_POST['valor']
is'0'
, the validation!empty($_POST['valor'])
will give us a false result , so it will not enter the condition.If we need the value not to be empty we can do it with the comparator
!==
in this wayWhich will lead us to another problem, what happens if the variable does not exist or is null?
I suggest that in order not to have false negatives we check that the variable exists and then check that it is not
''
, in this way:Another possibility would be to use a ternary operator, as follows:
Examples:
In the examples that follow, the variable
$status
takes one value or another depending on the case:Departure:
Departure:
Departure:
Greetings it should be this way