• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 407
  • Last Modified:

Need to get last digit of number - what's most efficient way?

I have a value:

$overall = "598397";  //for example

I need to get the last digit of that.

I've done a bit of research and have found two solutions commonly bantered about:

$last_digit = $overall % 10;

and

$last_digit = substr($overall, -1);

Which is the most efficient way to do this?

$overall will always be positive, will be '0' sometimes, and can grow quite large (low millions possible),

Thanks for any thoughts on this,

Chris
0
St_Aug_Beach_Bum
Asked:
St_Aug_Beach_Bum
  • 3
  • 2
1 Solution
 
Ray PaseurCommented:
I'd probably use either of those.  I think the results will usually be the same.
0
 
Ray PaseurCommented:
Or maybe not.  It will depend on the input you have.  

See http://www.laprbass.com/RAY_temp_staug.php

<?php // RAY_temp_staug.php
error_reporting(E_ALL);

$nums = array
( 1
, 123
, 0
, 42
, 3.1415926
, 1000000009
, "1,007"
)
;
foreach ($nums as $num)
{
    $mod = $num % 10;
    $sub = substr($num, -1);
    echo PHP_EOL . "<br>INPUT NUMBER: $num, MOD: $mod, SUBSTR: $sub";
}

Open in new window

Outputs:
INPUT NUMBER: 1, MOD: 1, SUBSTR: 1
INPUT NUMBER: 123, MOD: 3, SUBSTR: 3
INPUT NUMBER: 0, MOD: 0, SUBSTR: 0
INPUT NUMBER: 42, MOD: 2, SUBSTR: 2
INPUT NUMBER: 3.1415926, MOD: 3, SUBSTR: 6
INPUT NUMBER: 1000000009, MOD: 9, SUBSTR: 9
INPUT NUMBER: 1,007, MOD: 1, SUBSTR: 7

This is an artifact of PHP type juggling.

HTH, ~Ray
0
 
North2AlaskaCommented:
The question would be do you want the zero or a digit 1-9?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
St_Aug_Beach_BumAuthor Commented:
I'd want 0 through 9 - looks like substr it is :)

Thank you both!

Chris
0
 
St_Aug_Beach_BumAuthor Commented:
Thanks for running the test on these Ray -
0
 
Ray PaseurCommented:
Thanks for the points and thanks for using EE.  I always find it's better to run a quick test than to depend on anything in the PHP funhouse :-)  Happy New Year, ~Ray
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now