1

I have a multidimensional array with following values

$array = array( 
            0 => array (
               "id" => 1,
               "parent_id" => 0
            ),            
            1 => array (
               "id" => 2,
               "parent_id" => 1
            ),            
            2 => array (
               "id" => 3,
               "parent_id" => 1,
            )
            3 => array (
               "id" => 4,
               "parent_id" => 0
            )
            4 => array (
               "id" => 5,
               "parent_id" => 3
            )
         );

I want to find the count of children for particular id. In my case, I want the results to be like

find_children($array, 1);
// output : 2

find_children($array, 3);
// output : 1

I know this is done by using for loop. Is there any PHP array functions exist for this function?

4
  • array_map() function? Commented Oct 26, 2016 at 11:19
  • have you tried anything ? Commented Oct 26, 2016 at 11:20
  • you mean array_map() function Commented Oct 26, 2016 at 11:20
  • Yes. I did this by using for loop. But I want to know is there any PHP functions available for this Commented Oct 26, 2016 at 11:21

2 Answers 2

3

You can use count with array_filter

function doSearch($id, array $array) {

    $arr = array_filter($array, function ($var) use ($id){
        if ($id === $var['parent_id']) {
           return true;
        }
    });

    return count($arr);
}

or shorter version

function doSearch($id, array $array) {
    return count(array_filter($array, function($var) use ($id) {
        return $id === $var['parent_id'];
    }));
}

So basically it gets elements where $id is equal to parent_id and returns their count

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

Comments

2

You could implement it using array_filter, to filter the array down to the elements that match a given parent id, and then return the count of the filtered array. The filter is provided a callback, which is run over each element of the given array.

function find_children($array, $parent) {
  return count(array_filter($array, function ($e) use ($parent) {
    return $e['parent_id'] === $parent;
  }));
}

find_children($array, 1);  // 2
find_children($array, 3);  // 1
find_children($array, 10); // 0

Whether or not you prefer this to a loop is a matter of taste.

3 Comments

set parent_id to false and invoke function for $parent = 0 and it will count it as well
@Robert Whoops, I meant to write the test as ===, I've updated the answer.
that's way === is recommended, so you are sure that value that someone provides is value that you expect

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.