1

Okay, this small problem is driving me insane.

This is the print_r output of $strap_materials:

Array(
    [0] => steel
    [1] => leather
    [2] => polyester
    [3] => leather
    [4] => steel 
)

I want to count how many times each value exists and put each sum in an array within an array, just like this:

Array(
    [0] => Array(
        "name"  => steel
        "count" => 2
    )
    [1] => Array(
        "name"  => leather
        "count" => 2
    )
    [0] => Array(
        "name"  => polyester
        "count" => 1
    )
)

My intention is to use the newly created array like this:

foreach($straps as $strap) {
    echo "Name: " . $strap->name;
    echo "Count: " . $strap->count;
}

How can I achieve that?

3
  • Its very easy in Ruby. Commented Feb 28, 2013 at 21:02
  • RTLM: php.net/manual/en/function.array-count-values.php Commented Feb 28, 2013 at 21:03
  • 1
    @beck03076 we are talking about php not Ruby! Commented Feb 28, 2013 at 21:06

1 Answer 1

4

You can use array_count_values():

$counts = array_count_values($strap_materials);

foreach ($counts as $name => $count) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.