Jump to content

separate variable into sections of 3


hyster
Go to solution Solved by DavidAM,

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
Share on other sites

Try,

$int = 1234567890; 

$value = chunk_split ( $int , 3, "\n");

echo $value;

EDIT: If you are on windows machine add \r (not sure about that)

$int = 1234567890; 

$value = chunk_split ( $int , 3, "\r\n");

echo $value;
Edited by jazzman1
Link to comment
Share on other sites

  • Solution

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.