Deliver a 16-digit number in PHP

9

Number: 9999999999999999 It looks like this: 9999 9999 9999 9999

$num1 = "9999"; //parte 1
$num2 = "9999"; //parte 2
$num3 = "9999"; //parte 3
$num4 = "9999"; //parte 4

I would like to do this, without losing any number or adding anything, just leaving it in 4 parts in the order it was.

    
asked by anonymous 27.10.2017 / 15:28

4 answers

11

You can break this string in equal parts with the str_split() function that returns an array . It looks like explode() but instead of breaking the string by a delimiter str_split() does the same only, based on a fixed size.

$arr = str_split('9999999999999999', 4);

echo "<pre>";
print_r($arr);

Output:

Array
(
    [0] => 9999
    [1] => 9999
    [2] => 9999
    [3] => 9999
)

Another way to separate and format this string is chunk_split() that adds the ( s) character (s) at each interval, note that at the end of the string was also added an underline can remove it with rtirm() and specify the character you want to remove.

echo chunk_split('9999999999999999', 4, '_');
echo rtrim(chunk_split('9999999999999999', 4, '_'), '_');

Output:

9999_9999_9999_9999_
9999_9999_9999_9999
    
27.10.2017 / 15:30
7

Will it always be 16 digits ?? It can solve in a very simple way

$str = "9999999999999999";
$num1 = substr($str, 0, 4);
$num2 = substr($str, 4, 4);
$num3 = substr($str, 8, 4);
$num4 = substr($str, 12, 4);
  

Read more in Documentation

    
27.10.2017 / 15:34
7

Based on @rray's response

$separado = implode(' ', str_split('9999999999999999', 4));

If you wanted with dots:

$separado = implode('.', str_split('9999999999999999', 4));

As already explained, split divides the string into equal parts. In addition, implode "glue" the separated pieces, using a string of your choice between them.

If an extra space at the end is not a problem, see the more elegant alternative with chunk_split in the response mentioned.

If the number of digits varies and you want something like

99 9999 9999

You can use this alternative:

for($i=strlen($string); $i>0; $i-=4) $string=substr_replace($string, ' ', $i, 0);

It inserts spaces "from the end to the beginning". See working at IDEONE .

    
27.10.2017 / 15:44
3

If you take into account the decimal point in monetary terms, you will have to invert the value of the string in order to be able to punctuate correctly and then revert to have the original string value punctuated.

var_dump(formater("1234567891234567",5,"."));

function formater($str_number, $quantity, $char){
    $arr_number_reverse = array_reverse(str_split($str_number));
    $separado = implode($char, str_split(implode($arr_number_reverse), $quantity));
    return implode(array_reverse(str_split($separado)));
}

** Take the test, change the quantity of house to be applied to the chosen character ...

Based on the Bacco solution.

    
27.10.2017 / 18:15