I need to find the first and last number with length n and starting with digit d.
For example. i need to find the first and last number with length 6 and starting in 2 The result should be first number=200000 and last number=299999 .
I there any functions available in php to help me to get a logic to solve this.??
Hope Someone can help me..
You could try relying on the fact that the smallest number will end in all 0's and the largest in all 9's, and then use str_repeat
to generate the appropriate tailing digits:
echo $d . str_repeat('0', $n-1);
echo $d . str_repeat('9', $n-1);
For $d = 2
and $n = 6
, this will give you 200000
and 299999
.
If you need them as integers, just do
$start = (int)($d . str_repeat('0', $n-1));
$finish = (int)($d . str_repeat('9', $n-1));
var_dump($start);
var_dump($finish);
Output:
int(200000)
int(299999)
Here is an option which uses algebra to get the numbers you want. Based on the width of the number, we can compute the smallest number with that width. Then, the starting number is simply this value times the starting first digit. And the ending number can also be teased out.
$length = 6;
$first = 2;
$begin = pow(10, $length-1);
$start = $first * $begin;
$end = (($first + 1) * $begin) - 1;
echo $start . "
";
echo $end;
200000
299999
This should outperform the accepted answer because generating the numbers requires only a few arithmetic operations, rather than complex string manipulation operations.