Slicing strings from right to left

2

I have a column in the database with the name of codigo , in which the formatting looks like this:

18000001

Where 18 means the year we are and 1 is the code for each result. Knowing that this code can be greater than 1 I type 18000011 and so on, I need to remove only the final value before it reaches zero,

1800044 - Preciso pegar só o 44

1800444 - Preciso pegar o 444

1804444 - Preciso pegar o 4444
    
asked by anonymous 07.05.2018 / 15:10

2 answers

3

You can do it this way:

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

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

    
07.05.2018 / 15:16
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";
}
    
07.05.2018 / 15:16