1

I wish to count the values in the array Course that have the inner value Completed=>true. There are two values when I do a standard count. I have tried is_array and array_filter

count($employee['Course']

output: 2

Course(array)
    0(array)
        id:1
        name:Handling
        CoursesEmployee(array)
            id:1
            employee_id:1
            course_id:1
            completed(true)
     1(array)
         id:3
         name:Induction
         CoursesEmployee(array)
             id:2
             employee_id:1
             course_id:3
             completed(false)
5
  • 2
    How have you tried array_filter() and what was the result? Commented Nov 19, 2014 at 12:35
  • Yes I got 2 returned echo count(array_filter($course)); Commented Nov 19, 2014 at 12:36
  • result of var_dump ? Commented Nov 19, 2014 at 12:36
  • array_filter() takes an optional argument to specify a function that gets called for each element in your array. I'd suggest you start with that. Commented Nov 19, 2014 at 12:38
  • sorry no, it is the array structure Commented Nov 19, 2014 at 12:38

2 Answers 2

1

If you're using PHP 5.3 or higher, you may accomplish it via a single expression:

count(
  array_filter(
    $employee['Course'], 
    function($item){return $item['CoursesEmployee']['completed'];} 
  )
)

See docs on array_filter and anonymous functions.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, I have a better understanding of array_filter
1

You can also use array_reduce, which can grind an array down to a single result.

array_reduce( $employee['Course'], function( $carry, $item ) { 
  return $carry + (bool)$item['CoursesEmployee']['completed'] ) { 
}, 0 );

Using the fact that booleans have an int value of 0 for false or 1 for true.

Docs: http://php.net/manual/en/function.array-reduce.php

Comments

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.