-1
$cartItemsArray = ["", "1", "2", "3", "3", "4", "2", "3"];

for ($i = 0; $i < count($cartItemsArray); $i++) {
   echo $cartItemsArray[$i] . "<br />";
}

Here $cartItemsArray is an array of some id's. I want to count the occurences of every element and save it in an array.

I want output like below:

Array = [1:"1", 2:"2", 3:"3", 4:"1"];

I want to save these array.

Backstreet Imrul
  • 102
  • 2
  • 15

1 Answers1

2

You can use an array like this.

$cartItemsArray = ["", "1", "2", "3", "3", "4", "2", "3"];

$return = [];

foreach ($cartItemsArray as $card) {
    if (!isset($return[$card])) {
        $return[$card] = 0;
    }
    
    $return[$card]++;
}

Saromase
  • 467
  • 5
  • 10