Jump to content

separate variable into sections of 3


hyster

Recommended Posts

I want to separate a number into sections of 3 to make it easier to read

1234567890 into 123 456 789 0. the number is not going to be a set length

 

explode (as far as I can tell) uses a separator to do this IE: ; or - and I carnt find another function to do this

 

thx for any help

Link to comment
https://forums.phpfreaks.com/topic/278297-separate-variable-into-sections-of-3/
Share on other sites

is there a way to reverse the way the function works? start the count from the right instead of the left?

 

1234 chunk_split = 123 4 // looks a bit daft

1234 chunk_split /reverse = 1 234

 

Yes, I am a RegEx fan. 

 

http://www.regular-expressions.info/reference.html

If the value is actually a numeric value, you can use number_format, specifying a space as the thousands separator.

 

If the value is a string of characters limited to the digits 0 - 9, there are a couple of options: 1) Reverse the string, split it, then reverse the result; 2) Pad the string so the length is a multiple of 3, split it, remove the padding.

 

# An actual number
$int = 123456789;
echo number_format($int, 0, '.', ' ');

# A String - Reverse it, split it, reverse the result
$rev = strrev($int);
$split = trim(chunk_split($rev, 3, ' '));
echo strrev($split);

# A String - Extend it, split it, remove padding
$padded = str_repeat('?', 3 - (strlen($int) % 3)) . $int;
$split = chunk_split($padded, 3, ' ');
echo trim(str_replace('?', '', $split));
Of course, there is the brute-force method using a loop to build the output one character at a time, but it's much more code, and I'm too lazy to write it right now.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.