tags:

views:

64

answers:

5

How to count 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"

A: 
$number_of_elements = count($A)

http://uk2.php.net/manual/en/function.count.php

Svisstack
+1  A: 
$counts = array_count_values($value);

PHP man page

piddl0r
+3  A: 

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;
}
Victor Nicollet
A brave, possibly inspired, attempt at decryption =) +1
David Thomas
That would be my guess as to the meaning of this question
Mark Baker
A: 

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
Randolpho
A: 

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
)

tdtje