Activity Issue: How to Type PHP Zip Code Checker

Asked

Viewed 400 times

0

A matter of proof of logic

It is made from the sum of the 8 digits of the CEP, then subtract the result from the sum of the digits of the CEP of the multiple of 10 immediately superior to the result.

For example: CEP: 71010050 to 7 + 1 + 0 + 1 + 0 + 0 + 5 + 0 = 14 Subtract 14 out of 20. Validator = 6

I’ve done that part:

        $cepCliente = "41600-610";
        $cepClienteSemTraco = str_replace("-", "", $cepCliente);
        $cepClienteArray = str_split($cepClienteSemTraco);
        $cepClienteNumero01 = (int) $cepClienteArray[0];
        $cepClienteNumero02 = (int) $cepClienteArray[1];
        $cepClienteNumero03 = (int) $cepClienteArray[2];
        $cepClienteNumero04 = (int) $cepClienteArray[3];
        $cepClienteNumero05 = (int) $cepClienteArray[4];
        $cepClienteNumero06 = (int) $cepClienteArray[5];
        $cepClienteNumero07 = (int) $cepClienteArray[6];
        $cepClienteNumero08 = (int) $cepClienteArray[7];
        $cepClienteNumero09 = (int) $cepClienteArray[8];
        $somaCep = $cepClienteNumero01+$cepClienteNumero02+$cepClienteNumero03+$cepClienteNumero04+$cepClienteNumero05+$cepClienteNumero06+$cepClienteNumero07+$cepClienteNumero08+$cepClienteNumero09;

The rest I can’t do

  • 1

    Zip code has no validation, this is inaccurate...the only thing you can verify is if it has 8 digits.

  • @Ivanferrer It’s a matter of proof

  • 1

    you can also take from the webservice of the mail, or the url, and treat the entry of that page: https://viacep.com.br/ws/01001000/json/

1 answer

1


I don’t know if this kind of CEP validation is accurate, but given your need to find this validated, you can do something like.

    $cepCliente = "41600-610";
    $cepClienteSemTraco = str_replace("-", "", $cepCliente);
    $cepClienteArray = str_split($cepClienteSemTraco);
    $somaCep = 0;
    foreach ($cepClienteArray as $pos){
        $somaCep += $pos;
    }

According to its formula, it is now necessary to subtract from the multiple of 10 immediately higher than the result:

$multiplo = ceil($somaCep/ 10) * 10;
$validador = $multiplo - $somaCep;

The Ceil will round up the split result, so we multilayer that result by 10 to get the next multiple of 10.

  • 1

    Solved, thank you!

  • 2

    Don’t you think it’s better to wear one for to traverse all digits and compute the sum instead of a program line and a new variable for each digit?

  • @jsbueno I had only taken the op code and complemented the rest he asked, considered his comment and changed the sum to a more streamlined way

  • 2

    It would not be simpler to use the rest of the division operator: $validator = 10 - ($somaCep % 10); ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.