Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

php - Count number of values in array with a given value

Say I have an array like this:

$array = array('', '', 'other', '', 'other');

How can I count the number with a given value (in the example blank)?

And do it efficiently? (for about a dozen arrays with hundreds of elements each) This example times out (over 30 sec):

function without($array) {
    $counter = 0;
    for($i = 0, $e = count($array); $i < $e; $i++) {
        if(empty($array[$i])) {
            $counter += 1;
        }
    }
    return $counter;
}

In this case the number of blank elements is 3.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about using array_count _values to get an array with everything counted for you?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...