Cutting strings from right to left

Asked

Viewed 541 times

2

I have a column in the database named after codigo, where the formatting is like this:

18000001

Where the 18 means the year we are and the 1 is the code of each result. Knowing that this code can be greater than 1 digit 18000011 and so successively, I need to remove only the final value before reaching zero, example:

1800044 - Preciso pegar só o 44

1800444 - Preciso pegar o 444

1804444 - Preciso pegar o 4444

2 answers

3


You can do it this way:

$codigo = "1804444";
echo intval(substr($codigo, -5));

The substr function removes 18 from the string and then this string is converted to integer by returning in the case of the above 4444 example.

  • 2

    @Nicholasruschelkrüger if ever tested the code? because the answer friend logic is right!

  • @Nicholasruschelkrüger used the intval function precisely for this, as it does the integer conversion zeros are ignored.

  • 1

    yes, forgive me had not tested the code Ants to comment nonsense, thank you very much friend!

2

You can do it this way

$codigo = "";
$cod = 4444;
if($cod != ""){
    $anoAgora = substr(date("Y"),2,2);
    $ano =  substr($cod,0,2);
    $num =  substr($cod,2,5);
    $numInt = intval($num);
    if($anoAgora != $ano){
        $codigo = $anoAgora . "00001";
    }else{
        $numInt += 1;
        $strZeros ='';
        //obter o número de digitos que tem a variável 
        $num1 = strlen($numInt);
        //obter número de digitos(zeros) que faltam adicionar
        $num3 = ((5 - $num1));
        //criar a sequência de zeros em falta
        for($i=0;$i<$num3;$i++){
            $strZeros .='0';
        }
        $seqNum = $strZeros;
        $codigo = $ano . $seqNum . $numInt;
    }   
}else{
    $anoAgora = date("Y");
    $codigo = substr($anoAgora,2,2) . "00001";
}

Browser other questions tagged

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