I know question title seems quite 'un-understandable', but I don't know how to write question title for this particular question.
Question: I want to find factor for position.
Let me clear you with an example.
Value Factor
[Available] [Have to find out]
----------------------------------
1 10
3 10
9 10
10 10
11 10
25 10
50 10
75 10
99 10
100 100
101 100
105 100
111 100
127 100
389 100
692 100
905 100
999 100
1000 1000
1099 1000
1111 1000
4500 1000
6825 1000
7789 1000
9999 1000
10000 10000
10099 10000
51234 10000
98524 10000
99999 10000
100000 100000
and so on.
I hope you understand what I mean to get.
Assuming that the first three values should be 1 (as noted by Asaph), then you just need to use all that logarithm stuff you learned in school:
pow(10, floor(log10($n)))
So, how does this work? The base-10 logarithm of a number x
is the y
such that 10^y = x
(where ^
stands for exponentiation). This gives us the following:
log( 1) 0
log( 10) 1
log(100) 2
...
So the log10
of a number between 1 and 10 will be between 0 and 1, the log10
of a number between 10 and 100 will be between 1 and 2, etc. The floor
function will give you the integer part of the logarithm (we're only dealing with non-negative values here so there's no need to worry about which direction floor
goes with negative values) so floor(log10())
will be 0 for for anything between 1 and 10, 1 for anything between 10 and 100, etc. Now we have how many factors of ten we need so a simple pow(10, ...)
gives us the final result.
References:
I'm still a little unsure of what you're asking, but it seems like you want to map values to other values... In php arrays can be indexed with anything (making them a map). If 999 always means a factor of 100 and 1099 always means a factor of 1000, you can set the value of array[999] to 100 and the value of array[1099] to 1000, etc.
Basically Factor
is 10
to the power of number of digits in $value
minus 1
(except for the single digit numbers):
if($value < 10) {
$value += 10;
}
$numOfDigits = count(str_split($value,1));
$factor = pow(10,$numDigits-1);
This function should work for you. It seems like the first 3 "factors" in your list don't fit the pattern. If, in your sample data set, those first 3 "factors" should really be 1
instead of 10
, then you can safely remove the first 3 lines of the body of the function below.
function getFactor($num) {
if ($num < 10) { // If the first 3 "factors" listed
return 10; // in the question should be 1 instead of 10
} // then remove these 3 lines.
$factor = 1;
while($factor <= $num) {
$factor *= 10;
}
return $factor / 10;
}