I want to extract the last three characters from a number, an id.
For example:
Code: Select all
$id ='123456';
$nid ='456'; //this i need
Code: Select all
$id ='6';
$nid ='006'; //this i need
Code: Select all
$id ='123456';
$nid ='456'; //this i need
Code: Select all
$id ='6';
$nid ='006'; //this i need
Code: Select all
//return a number of $n characters from $id
// $n>0 return first $n characters / $n<0 return last $n characters
function getNId($id, $n){
$id = (string)$id;
$id = ($n>0) ? substr($id, 0, $n) : substr($id, $n);
$nr = abs($n) - strlen($id);
if($nr >0) for($i=0; $i<$nr; $i++) $id ='0'.$id;
return $id;
}
$id =123456;
$nid = getNId($id, -3);
echo $nid; // 456
//Examples
echo getNId('abc_xyz', -3); // xyz
echo getNId('11844', 3); // 118
echo getNId(8, -3); // 008
echo getNId(78, -3); // 078
echo getNId(78, 4); // 0078