Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count in array and Exception

Tags:

php

I have an example array:

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

I would like to check if MaxClass exists and additionally throw an error if there is more than one.

So I do:

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

For checking I'm adding:

$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 is better way than using variable $count?

Second question - what Exception class should I use? Maybe RuntimeException?

like image 590
serese Avatar asked Apr 07 '26 02:04

serese


2 Answers

You can use 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;
    }
}
like image 99
B. Desai Avatar answered Apr 09 '26 15:04

B. Desai


I'd 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 that divorces the sanity check from your "// different operations", but that's also exactly the point.

like image 35
deceze Avatar answered Apr 09 '26 14:04

deceze