Obtain part of the number without type conversion in PHP

Asked 1 years ago, Updated 1 years ago, 44 views

For example, if you have the number 12345 , you can use it
Can you keep the numbers separate like 123, 234, and 345? I thought of using Python to string and slice, but I want to keep the numbers.

php

2022-09-30 21:22

2 Answers

This is not limited to PHP, but if you want to find the last n digits of an integer value, you can use the remainder operation.

$num=12345;
$a = $num%1000;
echo$a."\n";//->345

If you want to take the middle n digits instead of the last n digits, you can divide it so that the digits you want to take are the last n digits and then do the same thing.

$b=intdiv($num,10)%1000;
echo$b."\n";//->234
$c = intdiv($num,100)%1000;
echo$c."\n";//->123

(From the operation of the PHP % operator, it seems to work normally with ($num/10) instead of intdiv($num,10), but just in case, I used intdiv. If intdiv does not exist, replace it with ($num)It's a bit troublesome to say that it's not a specific number of digits, but you can use power(10,$n) instead of 10, 100, 1000.

$m=2;//->From the `$m` digit counted from the lower order
Get $n=3;//->`$n` digits
$d = intdiv($num, power(10,$m))% power(10,$n);
echo$d."\n";//->123

It's not like you can see what you're doing just by showing the formula, so it might be better to use a string like Python's example.


2022-09-30 21:22

Below is how to use the positive look ahead of the regular expression.

$x=12345;
preg_match_all("/(?=(.{3}))/", "$x", $m);
var_dump(array_map(function($x){return(int)$x;},$m[1]))
=>                  
array(3){
  [0]=>int(123)
  [1]=>int(234)
  [2]=>int (345)
}

However, I will convert it to a decimal value, so if the string starts with "0", it will look like this:

$x=12045;
=>
// "045" (partial string) converted to 45 (integer value)
array(3){
  [0]=>int (120)
  [1]=>int (204)
  [2]=>int(45)
}


2022-09-30 21:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.