0

For example:

Array
(
[0] => Array
    (
        [id] => 1
        [name] => Test
        [slug] => test
        [services] => Array
            (
               [0] => Array
                   (
                       [name] => test
                   )
               [1] => Array
                   (
                       [name] => test
                   )
               [2] => Array
                   (
                       [name] => test
                   )
               [3] => Array
                   (
                       [name] => test
                   )
            )    
     )   
[1] => Array
    (
        [id] => 1
        [name] => Test
        [slug] => test
        [services] => Array
            (
               [0] => Array
                   (
                       [name] => test
                   )
               [1] => Array
                   (
                       [name] => test
                   )
               [2] => Array
                   (
                       [name] => test
                   )
               [3] => Array
                   (
                       [name] => test
                   )
            )    
     )  

This is simply dummy data, however I want to count the amount of services that are inside each array but I'm looking for an efficient way.

Now the way I was going to do this was:

foreach($arrayAbove as $array){

    $i = 0;
    foreach($array['services'] as $array){
        $i++;
    }
}

Is there a better way to do this?

3 Answers 3

4
foreach($arrayAbove as $array){

    $i = count($array['services']);
    print_r($i);
}

if you want overall count:

$i = 0;
foreach($arrayAbove as $array){

     $i += count($array['services']);
}
print_r($i);
Sign up to request clarification or add additional context in comments.

Comments

1

Here's a fun way:

$result = array_reduce($array, function($c, $v) { return $c + count($v['services']); });

Comments

0

Use PHP sizeof() Function

foreach($arrayAbove as $array){

    $sub_array = sizeof($array['services']);           
    $total = $total + $sub_array;
}

echo 'Sub Array count is : '.$total;

4 Comments

@Random size of gives the count
actually $total = $total + $sub_array; contain count
@Random I suppose that depends on what you mean by "have to." You will get a notice if you don't, but it will still work.
@Don'tPanic Yeah, if you can avoid a notice by adding a line, you have to do it, imo, to clear up logs... :)

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.