This is probably an easy one. I need to check to see if an array which will have 4 or 5 values, has all empty values. If they are all empty (sometimes they may all be null. ) I will do one thing. If even a single key has a value, then I will do something else.
The array is created from fields in a database, with something like this:
It seems like there has to be an easier way than that. I’ve been trying empty() and is_null(), but they don’t seem to do the trick. Any other suggestions out there?
If you know the array will only contain 4 or 5 values, and you need to do a specific action depending on which of the values are null, then you should use if sentences.
For example:
if (empty($types[0])) do whatever
etc
mithra62:
If the array would need to be changed, so would the rest of the code. One of the points to the author was that he needed to do a specific action depending on which of the array input was missing. Hence even if you use a loop, you either need if sentences or a switch in any case to make sure the action happens.
The code below might look nicer, but it will require more resources to run, and you can specify the different rules on each array input as you can with if sentences.
foreach ($types as &$key => $value) {
if (empty($value)) {
switch ($key) {
case 0:
//do something
break;
case 1:
//do something
break;
case 2:
//do something
break;
default:
//do something
break;
}
}
}
perhaps you could try flipping the keys
adding up the values of the array is flawed since it treats chars as 0
I think regardless of what method you use, , in the end either you or the php engine would have to “loop”. So why not make it easier to read by looping it yourself?
Thanks for the replies. I guess it wasn’t a totally dumb question as there doesn’t seem to be one clear choice for the way to do this. Here is what I wound up doing:
foreach($types as $key => $value) {
if ($value!=''){
$emptycheck = 1;
break;
}
else {
$emptycheck = 0;
}
}
I also tried stereofrog’s suggestion, and that also seems to work well and be short and sweet:
if(count(array_filter($array)) == 0)
all values are empty