38

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?

1
  • @MadaraUchiha a count addition inside a loop (whichever may be best) may be better, since you dont have to iterate everything. Commented Apr 27, 2018 at 8:14

8 Answers 8

78

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));
Sign up to request clarification or add additional context in comments.

Comments

34
$count = 0;
foreach ($array as $type) {
    $count+= count($type);
}

Comments

34

Use Count Recursive and subtract the First level count, like this:

count($mainArr, COUNT_RECURSIVE) - count($mainArr);

If your array has +3 levels, just add [?] keys:

count($mainArr[1], COUNT_RECURSIVE) - count($mainArr[1]);

5 Comments

what if i have 4 dimensional array?
Excellent! @nashwa, recursive will count every element IIRC, no matter how deep
For me count($arr, COUNT_RECURSIVE) was sufficient but great answer as it allows more depth
php.net/manual/en/function.count.php for more details on the mode flag.
Note: COUNT_RECURSIVE appears to count keys, not values, which is why if you use it on e.g. [ [1,2,3], [], [4,5,6] ], you will get 9 instead of 6. Because this array is really [ 0=>[0=>1, 1=>2, 2=>3], 1 => [], 2 =>[0=>4,1=>5,2=>6] ] This is why OP here recommends subtracting count($mainArr).
3

:)

$test = array (
    array (
        'test','test','test'
    ),
    array (
    'test','test'
    ),
    array (
        array (
        'test'
        ),
        array (
        'test','test','test','test'
        )
    )
 );
 echo "  array count ". count($test[0]) ." <br /> ";
 echo "  array count ". count($test[1]) ." <br /> ";
 echo "  array count ". count($test[2]) ." <br /> ";
 echo "  array count ". count($test[2],1) ." <br /> ";
 echo "  array count ". (count($test[2],1) - count($test[2])) ." <br /> "; // all child num - parent num
 echo "  array count ". count($test[2][1]) ." <br /> ";

output:

array count 3

array count 2

array count 2

array count 7

array count 5

array count 4

Comments

2

The easiest way to do this is one simple foreach loop:

$count = 0;
foreach( $tickets as $ticketType){
    $count += count( $ticketType);
}

2 Comments

This should work, but your variable naming is really confusing (confused?)
@FrostyZ I had misspell there, fixed, I've also prefixed $type so it'll be clearer what's in them.
0

You can try using array_walk_recursive()

$totalTickets = 0;

array_walk_recursive($tickets, function($item) use (&$totalTickets) {
    $totalTickets++;
});

Comments

0

For those who reach this topic and needs to Count items in multi-dimensional Object...

1. Convert Object to Array
The Object must be first converted into an Array, here do it in two steps using PHP build in functions to convert the Object into JSON string using json_encode() and then decode the JSON string back to the Array using json_decode() with second parameter set to true make the response an associative array.

2. Count items in the Array
Count the multi-dimensional array as bigkm's answer did it in three steps, ie using array_map() that calls count() function to count items and finally array_sum() functions to sum the counted items.

All five steps as liner is:

$totalTickets = array_sum(array_map("count", json_decode(json_encode($tickets), true)));

Note: all nested levels must be of type Countable|array otherwise an Fatal error is triggered by count() function.

I will use approach posted by bigkm's answer.

// The object of tickets
$tickets = new StdClass;
$tickets->type1 = new StdClass;
$tickets->type1->ticket1 = new StdClass;
$tickets->type1->ticket2 = new StdClass;
$tickets->type1->ticket3 = new StdClass;

$tickets->type2 = new StdClass;
$tickets->type2->ticket4 = new StdClass;
$tickets->type2->ticket5 = new StdClass;
$tickets->type2->ticket6 = new StdClass;
$tickets->type2->ticket7 = new StdClass;

$tickets->type3 = new StdClass;
$tickets->type3->ticket8 = new StdClass;

// Convert the multi-dimensional Object into Array through JSON conversions
$ticketsArray = json_decode(json_encode($tickets), true);

// Finally count items using 
$totalTickets = array_sum(array_map("count", $ticketsArray ));

print($totalTickets);
// $totalTickets --> 8

// or one liner
$totalTickets = array_sum(array_map("count", json_decode(json_encode($tickets), true)));

print($totalTickets);
// $totalTickets --> 8

Comments

-1

To count total number of Ticket, this bellow code will help you for PHP.

foreach($mainArray as $Array){
    foreach($Array as $perTicke){
        $count++;
    }
}
$total_ticket = $count;

1 Comment

Don't do a inner foreach loop just to obtain a count of elements.

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.