0

I need to ensure that all the elements in my array are empty strings to process an action. The way I am currently doing it is incrementing a variable each time an element is an empty string. Then I check the value of that variable against a certain requirement N. If N is met, the action is processed. Below is the snippet of the code that checks for empty strings. I am not sure if this is the best way to do it and think there has to be a better way to do it because basically I am hard coding that value N. Can anybody else suggest another approach?

function checkErrorArray($ers) {
    $err_count = 0;
    foreach ($ers as &$value) {
        if ($value == '') {
            $err_count++;
        }
    }
    return $err_count;
}
1
  • Well as you already say it works, the only thing is that you could write it differently like just: return array_count_values($ers)[""]; Commented Mar 26, 2016 at 20:21

2 Answers 2

3

Why don't you do:

function areAllEmpty($ers) {
    foreach ($ers as &$value) {
        //if a value is not empty, we return false and no need to continue iterating thru the array
        if (!empty($value)) return false;
    }
    //if got so far, then all must be empty
    return true;
}

It will not have to run through the whole array if a non-empty value is found.

You could also do a shorter version:

function areAllEmpty($ers) {
        $errs_str = implode('', $ers);//join all items into 1 string
        return empty($errs_str);
    }

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

2

Just filter it and if it is empty then ! will return true if not empty it will return false:

return !array_filter($ers);

Or if you actually need the count of empty elements then:

return count(array_diff($ers, array_filter($ers)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.