When building an array from an array: IF var is SET, INCREMENT else SET to 1

50 Views Asked by At

Hi i've tried many solutions, but can't find what i'm after. I'm building an array from a number of other arrays, I could do something like this:

isset($setinc) ? $setinc++ : $setinc=1;

However when when the var is:

$output[ $data[ 'electoral_nation' ] ][ 'regions' ][ $data[ 'electoral_region' ] ][ 'constituencies' ][ $data[ 'electoral_constituency_id' ] ][ 'national_candidates' ]

It all gets very messy when there are over 600 comparisons and loops, is there a way I can simplify it rather than this?

isset($output[ $data[ 'electoral_nation' ] ][ 'regions' ][ $data[ 'electoral_region' ] ][ 'constituencies' ][ $data[ 'electoral_constituency_id' ] ][ 'national_candidates' ]) ? $output[ $data[ 'electoral_nation' ] ][ 'regions' ][ $data[ 'electoral_region' ] ][ 'constituencies' ][ $data[ 'electoral_constituency_id' ] ][ 'national_candidates' ]++ : $output[ $data[ 'electoral_nation' ] ][ 'regions' ][ $data[ 'electoral_region' ] ][ 'constituencies' ][ $data[ 'electoral_constituency_id' ] ][ 'national_candidates' ]=1;

I'm running PHP8 so the null coalescing operator is an option, but can't quite get my head round it. This is to stop the Undefined Array Key error.

Thanks in advance!

Edit: Ok so some of the above is appearing to be a distraction. Therefore, to clarify. Is there a way of writing the following but only declaring $setinc ONCE

isset($setinc) ? $setinc++ : $setinc=1;

i.e.

isset($setinc) ? += 1 : == 1;
1

There are 1 best solutions below

0
JC Cavalca On

It's not a perfect example because you have to change the naming, but I think it's enough short and clean. A last thing, you have to check the key $electoralConstituencyId in 'constituencies' exist in else case. In this example, I doesn't that.

$electoralNation = $data[ 'electoral_nation' ] ?? null;
$electoralRegion = $data[ 'electoral_region' ] ?? null;
$dataElectoralConstituencyId = $data[ 'electoral_constituency_id' ?? null;

if (null === $electoralNation || null === $electoralRegion || null === $dataElectoralConstituencyId) {
    throw exception;
}

$keysInRightOrder = [$electoralNation, 'regions', $electoralRegion, 'constituencies', $electoralConstituencyId];

if ($this->arrayKeysInOrderExists($keysInRightOrder, $output)) {
    $output[$electoralNation]['regions'][$electorRegion]['constituencies'][$electoralConstituencyId]++;
} else {
    $output[$electoralNation]['regions'][$electorRegion]['constituencies'][$electoralConstituencyId] = 1;
}


public function arrayKeysInOrderExists(array $keys, array $array): bool
{
    foreach ($keys as $key) {
        if (array_key_exists($key, $array)) {
            $array = $array[$key];
        } else {
            return false;
        }
    }
    
    return true;
}