count works exactly as you would expect, e.g., it counts all the elements in an array (or object). But your assumption about the array containing four elements is wrong:

  • "1" is equal to 1, so 1 => "B" will overwrite "1" => "A".
  • because you defined 1, the next numeric index will be 2, e.g. "C" is 2 => "C"
  • when you assigned 2 => "D" you overwrote "C".

So your array will only contain 1 => "B" and 2 => "D" and that's why count gives 2. You can verify this is true by doing print_r($a). This will give

Array
(
    [1] => B
    [2] => D
)

Please go through Arrays again.

Answer from Gordon on Stack Overflow
🌐
PHP
php.net › manual › en › function.array-count-values.php
PHP: array_count_values - Manual
array_count_values() returns an array using the values of array (which must be ints or strings) as keys and their frequency in array as values. ... Returns an associative array of values from array as keys and their count as value.
🌐
TutorialsPoint
tutorialspoint.com › array-count-values-function-in-php
PHP array_count_values() Function
July 30, 2019 - The array_count_values() function returns an associative array of values using the values of the input array as keys and their frequency in input array as values. It returns an associative array of values from input as keys and their count as value.
🌐
CodeSignal
codesignal.com › learn › courses › php-associative-arrays-in-practice-revision-and-application › lessons › efficient-element-counting-with-associative-arrays-in-php
Efficient Element Counting with Associative Arrays in PHP
When the above PHP code executes, it displays the counts for each color: ... We began with an empty associative array. Then, we went through our list, and for every occurring element, we simply incremented its value in the associative array.
🌐
W3Schools
w3schools.com › php › func_array_count_values.asp
PHP array_count_values() Function
Loops While Loop Do While Loop For Loop Foreach Loop Break Statement Continue Statement PHP Functions PHP Arrays · Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Functions ...
🌐
Tutorialdeep
tutorialdeep.com › knowhow › php faqs › how to find length of associative array using php
How to Find Length of Associative Array Using PHP
January 9, 2021 - To get the length of an associative array, you can use the PHP count(). It takes an argument as the associative variable that contains the elements of array in PHP.
Find elsewhere
🌐
TutorialKart
tutorialkart.com › php › php-array-count-values
PHP array_count_values() - Count all the occurrences of values in array - Examples
May 7, 2023 - PHP array_count_values() function counts the occurrences of all values in an array and returns an associative array formed by the unique value of input array as keys, and the number of their occurrences in the array as values.
🌐
Codecademy
codecademy.com › docs › php › arrays › array_count_values()
PHP | Arrays | array_count_values() | Codecademy
August 8, 2023 - The array_count_values() is a function that counts the occurrences of values in an array. It accepts an input array and returns an associative array, where the keys are the unique values found in the array, and the corresponding values are the ...
🌐
Stack Overflow
stackoverflow.com › questions › 21574662 › associative-array-count-php
Associative Array Count Php - Stack Overflow
... I edited again question. ... If you are using PHP 5.5 , you could do like this.. Since you needed unique as per your comment. echo count(array_unique(array_column($arr,'element1')));
🌐
W3Schools
w3schools.com › php › func_array_count.asp
PHP count() Function
Loops While Loop Do While Loop For Loop Foreach Loop Break Statement Continue Statement PHP Functions PHP Arrays · Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Functions ...
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-array_count_values-function
PHP array_count_values() Function - GeeksforGeeks
June 20, 2023 - The array_count_values() is an inbuilt function in PHP which is used to count all the values inside an array. In other words we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array.
🌐
SitePoint
sitepoint.com › php
Count total items in a multidimensional array/ associative array, php - PHP - SitePoint Forums | Web Development & Design Community
July 23, 2010 - Array ( [upload] => Array ( [name] => Array ( [0] => 1024x768.jpg [1] => 1280x800.jpg [2] => 1280x1024.jpg [3] => 1440x900.jpg ) [type] => Array ( [0] => image/jpeg [1] => image/jpeg [2] => image/jpeg ...
Top answer
1 of 2
1

Update #2. Lots of information, let me know if I lose you.

I made a couple tiny mistakes (needed to pass $current + 1 instead of $current++, and $levels[$current]++ was in the wrong place) in the last code. I tested this update with your example data; it will work for you. Basically, calc() is a recursive function that goes through every level of the array, counting each index that is an array, and adds that count to the master "counting" array ($levels). You can stick this right into your class, as I did below.

It doesn't return anything on purpose. $levels is passed by reference, and the count of each level is updated directly on it. So the first variable you pass to calc() will be turned into an array, like the one you're looking for in your question.

If your class script looks exactly like that, you should be getting errors. After class someName {, you should only be defining functions and variables. Code that actually performs an action, such as using echo or setting $test = new Test();, needs to be placed after the class definition.

With that said, if you want to execute some code every time you initiate this class, you should put this code in the class's constructor.

Below is what I think you want your class to look like. If you want $data to be in the class, declare the variable with var $data and fill it inside the constructor. If you're confused, let me know and I can update my answer again.

// Your class
class Test
{
    // Counts the number of arrays in each level of $data
    function calc(&$levels, $current, $parent)
    {
        if (!isset($levels[$current])) {
            $levels[$current] = 0;
        }
        foreach($parent as $child) {
            $levels[$current]++;
            if (is_array($child)) {
                $this->calc($levels, $current + 1, $child);
            }
        }
    }
}

// Let's use the class! Create an instance of it
$test = new Test();

// Fill the data array
$data = array();
$data['food']['soup']['chicken_noodle'] = '';
$data['food']['soup']['tomato'] = '';
$data['food']['soup']['french onion'] = '';
$data['food']['salad']['house'] = '';
$data['food']['salad']['ceasar'] = '';
$data['drink']['soda']['coke'] = '';
$data['drink']['soda']['sprite'] = '';
$data['drink']['soda']['dr pepper'] = '';
$data['drink']['alcoholic']['whiskey']['Jim Beam'] = '';
$data['drink']['alcoholic']['whiskey']['Jameson'] = '';
$data['drink']['alcoholic']['whiskey']['Bushmills'] = '';
$data['drink']['alcoholic']['vodka']['Stolichnaya'] = '';
$data['drink']['alcoholic']['vodka']['Ketel One'] = '';
$data['drink']['alcoholic']['vodka']['Grey Goose'] = '';
$data['drink']['alcoholic']['vodka']['Belvedere'] = '';
$data['drink']['alcoholic']['rum']['Captain Morgan'] = '';
$data['drink']['alcoholic']['rum']['Bacardi'] = '';    

// Count the data for arrays on each level
$count = array();
$test->calc($count, 0, $data);

// Print the results
echo '<pre>';
print_r($count);
exit ('</pre>');
2 of 2
0

If you want to get the sum of all the elements in all the arrays, you can use

count($arr, COUNT_RECURSIVE);

Try it online

🌐
Reintech
reintech.io › blog › phps-array-count-values-function-complete-guide
PHP's `array_count_values()` Function: A Complete Guide
April 14, 2023 - The array_count_values() function accepts an array as input and returns an associative array where keys represent unique values from the input, and values represent their occurrence counts.