Array Counting and Exception

I have an example of an array:

$array = [
    [
        FirstClass,
        SecondClass,
        ThirdClass,
    ],
    [
        ThirdClass,
        MaxClass
    ],
    [
        FirstClass,
        ThirdClass
    ],
    [
        SecondClass,
        FirstClass,
    ]
];

      

I would like to check if MaxClass exists and furthermore throws an error if there are more of them.

So I:

foreach ($array as $class) {
    if (get_class($class) == 'MaxClass') {
        //different operations
    }
}

      

To check, I add:

$count = 0;
foreach ($array as $class) {
    if (get_class($class) == 'MaxClass') {
        if ($count < 2) {
        //different operations
        } else {
            throw new Exception('Too many MaxClass!');
        }
    }
}

      

But maybe better than using the $ count variable?

The second question is which exception class should I use? Maybe a RuntimeException?

+3


source to share


4 answers


I would go for something like this with a functional approach:

class ReachedMaxLimitException extends LogicException {}

$count = array_reduce(
    call_user_func_array('array_merge', $array),  // flatten array
    function ($count, $o) { return $count + ($o instanceof MaxClass); }, 
    0
);

if ($count > 1) {
    raise new ReachedMaxLimitException;
}

      



Obviously, the sanity check is being divorced from your " // different operations

", but that's also the point.

+1


source


You can use a flag variable to check: Try this solution:



$found_max_class=false;
foreach ($array as $class) {
    if (get_class($class) == 'MaxClass') {
       if($found_max_class)
        {
            throw new Exception('Too many MaxClass!');
        }
        $found_max_class =true;
    }
}

      

+3


source


<?php

$array = [
    [
        "FirstClass",
        "SecondClass",
        "ThirdClass",
    ],
    [
        "ThirdClass",
        "MaxClass"
    ],
    [
        "FirstClass",
        "ThirdClass"
    ],
    [
        "SecondClass",
        "FirstClass",
        "MaxClass"
    ]
];

$countValues = array_count_values(array_reduce($array, 'array_merge', array()));

var_dump($countValues["MaxClass"]);

if($countValues["MaxClass"] > 1) {
    throw new Exception('Too many MaxClass!');
}

      

see the example here: http://sandbox.onlinephpfunctions.com/code/9a27d9388b93c4ac4903891517dc8ad531f04a94

+1


source


$restrictions = [MaxClass::class => ['max' => 1, 'found' => 0]];

foreach($array as $subArray) {
    foreach($subArray as $element) {
        $className = get_class($element);

        if (isset($restrictions[$className]) {
            if ($restrictions[$className]['found'] >= $restrictions[$className]['max']) {
                // throw your exception
            }

            $restrictions[$className]['found'] += 1;
        }

        // code
    } 
}

      

+1


source







All Articles