I have a multi-dimentional array set up as follows
array() { ["type1"] => array() { ["ticket1"] => array(9) { // ticket details here } ["ticket2"] => array(10) { // ticket details here } ["ticket3"] => array(9) { // ticket details here } } ["type2"] => array() { ["ticket1"] => array(9) { // ticket details here } ["ticket2"] => array(10) { // ticket details here } ["ticket3"] => array(9) { // ticket details here } } }
etc.
I am trying to get a count of the total number of tickets in the array (number of second level items), but the number of types is variable as are the number of fields that each ticket has, so I cannot use COUNT_RECURSIVE and maths to get the number.
Can anyone help me?
Syntax – count() If you pass multidimensional array, count($arr) returns length of array only in the first dimension. If you want to count all elements in a multidimensional array recursively, pass COUNT_RECURSIVE as second argument, as shown in the following code sample.
How to Count all Elements or Values in an Array in PHP. We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array.
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
A bit late but this is a clean way to write it.
$totalTickets = array_sum(array_map("count", $tickets));
Assuming $tickets
is your multi-dimensional array.
I've expanded the code to give an explained example because array_map might be new to some
$tickets = array( "type1" => array( "ticket1" => array(), "ticket2" => array(), "ticket3" => array(), ), "type2" => array( "ticket4" => array(), "ticket5" => array(), "ticket6" => array(), "ticket7" => array(), ), "type3" => array( "ticket8" => array() ) ); // First we map count over every first level item in the array // giving us the total number of tickets for each type. $typeTotals = array_map("count", $tickets); // print_r($typeTotals); // $type_totals --> Array ( // [type1] => 3, // [type2] => 4, // [type3] => 1 // ) //Then we sum the values of each of these $totalTickets = array_sum($typeTotals); print($totalTickets); // $totalTickets --> 8
So because we don't care about the intermediate result of each type we can feed the result into array_sum
$totalTickets = array_sum(array_map("count", $tickets));
$count = 0; foreach ($array as $type) { $count+= count($type); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With