Home > other >  Find a way to check this table without if else statements
Find a way to check this table without if else statements

Time:04-26

I have the following image to show what I need to do.

enter image description here

The data I have is the one marked in blue, and according to that I need to get the results of the one marked in red.

So for example my client have the next data:

ingreso bancarizacion ult 6 ult 12 ult 24
SI SI NO NO NO

The result will be:

Calificacion Tipo Clientes Resultado
A 1 APTO

Can anyone help me achieve this in PHP without nesting a lot of if/else statements?

I need a function to return an array with the 3 results.

function checkClient($ingreso, $bancarizacion, $ult6, $ult12, $ult24){
    $data =  [];

    // conditions
    
    return $data;    
}

Thanks in advance!

CodePudding user response:

You have to do manual indexes for each column, but it has no reason to do it by yourself since it is one of the things that databases do. If you'll put this data in a database (let's say MongoDB) and set indexes for all these columns. You'll be able to find matches pretty fast with an elegant code.

CodePudding user response:

An easy way to accomplish this without conditional constructs is concatenating the relevant fields into "lookup strings" and then matching the resulting strings with mapped results. We're using the match statement here (PHP 8), but you could also do associative array lookups.

function checkClient($ingreso, $bancarizacion, $ult6, $ult12, $ult24) {

    // Calificacion => Mapped from: ingreso   bancarizacion

    $calci = match($ingreso . $bancarizacion) {
        'SISI' => 'A',
        'SINO' => 'B',
        'NOSI' => 'C',
        'NONO' => 'D',
        default => '?'
    };
    
    // Tipo, Resultado => Mapped from: ULT6   12   24

    $tipo_resu = match($ult6 . $ult12 . $ult24) {
        'NONONO' => [1, 'APTO'], 
        'NONOSI' => [2, 'APTO'], 
        'NOSINO' => [3, 'REVISARE'], 
        'NOSISI' => [4, 'REVISARE'], 
        'SI' => [5, 'NO APTO'],
        default => [0, 'OBSCURO']
    };
    
    return [
        'Calificacion' => $calci,
        'Tipo Clientes' => $tipo_resu[0],
        'Resultado' => $tipo_resu[1]
    ]; 
}

No ifs or buts required. :) Map/case lookups, whether using match, switch or associative arrays, are often a convenient way to avoid elaborate if/else constructs and chains of multiple evaluations. You could also do match(true) { with arms like $ult6 == 'NO' && $ult12 == 'NO' && $ult24 == 'SI' => [2, 'APTO'], but concatenation is compact and sufficient for this case.

You could also implement this logic on a database level e.g. with case statements, though maintaining it would likely be more work. I'll leave that exercise for someone else to tackle.

  • Related