I’m late, but I hope I can help someone:
I bumped into a case where it is necessary to check an index of a array
, using the other examples, you may get the error Undefined Index
. Generally use the empty()
, to test values in arrays
because he doesn’t give a warning
if the index does not exist.
In the case 0
is a considered value empty
and if you try to access an index of a array
which does not exist, the warning
previously mentioned will be released.
So I arrived at the following solution:
if (empty($array['age']) && @$array['age'] !== 0) {
throw new RuntimeException('Idade não informada.', 400);
}
Note that I used the operator @
, that suppresses the warinings
on that line, that is NOT a recommended practice, but that in this case, only a simple and isolated part of the code is affected and will not bring problems.
In place of @$array['age'] !== 0
, you might think about using isset($array['age'])
, but the isset
considers the value in $array['age'] = null
as false
.
It is a pity that in PHP still by default gives this type of problem (for example Javascript allows access to indexes not defined), but that can be changed in the settings, the big problem is not treat the index before performing some action, how to access the method of an undefined index, so always be careful with this type of data manipulation, which can generate unexpected bugs in the application.
Can do
}else if (empty($idade) || $idade == 0){
. But explain better than types of value$idade
may have we can be clearer in helping...– Sergio
age can only have two digits. Ex: 34. But I want 0 to also be accepted.
– ivan veloso
If you use
(empty($idade) || $idade == 0)
There will be problems, you are checking if the age is empty or if the age is equal to zero. His problem I believe occurs when age is a valid age, but he recognizes it as empty by being zero.– Pedro Henrique
That’s right @Pedro Henrique
– ivan veloso
@Ivanveloso, you wrote in the comments: "But I want 0 to be accepted as well." This is what you want?
– Sergio