30
$items = explode(',',$product); // values is 4,2,4,2,2,4

$unique_items=array_unique($items); // gives me 4,2

What code should be next to give me 4 = 3 , 2 = 3 and store the number of values to a variable?

1
  • Do a loop, for n-times (n being the number of elements in $items), then. extract each character at $i ($i would be the current number of loops, also the offset into the string, that is you do for($i=0; i<count($items); $i++){...}) and match that character to each element inside $unique_items, increase a counter variable each time the character inside $unique_items and $items[$i] match, and that's it! You can figure out the code yourself, since I'm a bit rusty with php commands. Commented Jun 20, 2011 at 7:44

2 Answers 2

56

see: array_count_values

Like:

$occurences = array_count_values($items);
print_r($occurences);

Output:

Array
(
    [4] => 3
    [2] => 3
)

Usage:

echo $occurences[4]; // outputs 3
Sign up to request clarification or add additional context in comments.

3 Comments

how to store the value of 3 to a variable? tnx
@yohdaman See the updated code. You have all the information in $occurences. If you want to access them, use: $occurences[4] for example.
tnx to all!! very much appreciated. =)
4

You're probably looking for array_count_values() function.

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.