Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array is a collection of specific object?

Tags:

arrays

object

php

In my class I have a method which expects as array, and this array should be used differently depending on the collection type. The array items should be objects, and I need to know which class instance these objects are.

For example: in the array($obj1, $obj2), I need to check the instance of these objects, which class they were created from.

Here some code:

public function convertDataToInsert($data)
{
    if (is_array($data)) {
        foreach ($data as $obj) {
            if ($obj instanceof CriterioDigital) {
                //Ok, an array of CriterioDigital
            } elseif ($obj instanceof ArquivoDigital) {
                //Ok, an array of ArquivoDigital
            } else {
                throw new \Exception('Invalid parameter');
            }
            break;
        }
    }

Or maybe:

public function convertDataToInsert($data)
{
    if (is_array($data)) {
        $obj = $data[0];
        if ($obj instanceof CriterioDigital) {
            //Ok, an array of CriterioDigital
        } elseif ($obj instanceof ArquivoDigital) {
            //Ok, an array of ArquivoDigital
        } else {
            throw new \Exception('Invalid parameter');
        }
    }
}

I only need to check the collection type of this array. I know I can iterate it, but is there any better way in php to do so?

like image 294
Siipe Avatar asked Jul 27 '17 14:07

Siipe


1 Answers

Use an array filter :

if (count(array_filter($data, function ($entry) {
        return !($entry instanceof CriterioDigital);
})) > 0) {
    throw new \DomainException('an array of CriterioDigital must be provided');
}
like image 107
ceadreak Avatar answered Oct 13 '22 19:10

ceadreak