开发者

Count array elements after the given element

How to c开发者_开发知识库ount array elements after the first occurrence of a given element?

For example

 $a = array('a', 'c','xxd','ok','next1','next2');
 echo occurences_after($a, 'ok'); 

should print "2"


If you're looking for the number of elements after the first occurrence of a given element:

function occurences_after($array, $element)
{
  if ( ($pos = array_search($element, $array)) === false) 
    return false;
  else
    return count($array) - $pos - 1;
}


$counts = array_count_values($value);

PHP manual page


If I read your question correctly, the way to count the number of elements that match a particular element in an array is to loop over the array and check each element individually for a match. This smells like homework, so I'm not going to write the code for you, because it's trivial, but it should get you going in the right direction.

So to reiterate:

  • loop over every element in the array
  • check each element to see if it matches the requirement
  • if it does, increment the number of items found


I'm not sure what you mean. If you want to count the amount of elements in the array $A.

You can use count($A)

If you want to count the values:

print_r(array_count_values($A));

The output will be:

Array
(
    [a] => 1
    [c] => 1
    [xxd] => 1
    [ok] => 1
    [next1] => 1
    [next2] => 1
)


$number_of_elements = count($A)

Reference: manual page on count()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜