Page 1 of 1

Extract last N characters from a number

Posted: 02 Mar 2018, 17:38
by Marius
Hello,
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
And, if the id has less than three characters:

Code: Select all

$id ='6';
$nid ='006'; //this i need
What php code to use to get that $nid?

Extract last N characters from a number

Posted: 02 Mar 2018, 17:48
by Admin
Hello,
You can use in your php code the getNId() function from the following example.
It returns the first or the last $n characters from a number or string.

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