View Full Version : splitting a number

11-23-2011, 08:54 PM
this is probably simple...but can someone help me out.
i have variable $var=some number.the number can be of any length.examples 112,9912 etc.
i need to split each digit and seperate it by a /
For example,if $var=6066, I need to split it and store in a variable as /6/0/6/6/..

11-23-2011, 09:00 PM
Not sure if you intended to include that comma in the number or not, but this handles with/without comma:

$numbers = array('123456', '123,456');

foreach($numbers as $v)
$v = str_replace(',', '', $v);
var_dump('/' . implode('/', str_split($v, 1))); // outputs "/1/2/3/4/5/6"

11-23-2011, 09:03 PM
There are several ways to accomplish this. I'm lazy, so I'd make use of wordwrap to force it.

$num = 6066;
$separated = wordwrap($num, 1, "/", true);

Super easy to do. You'll need to prepend and append the / if you want to keep it, but that's easy enough to do.

11-23-2011, 10:55 PM
This will remove all non-digits (commas, etc) as well as append/prepend slashes:

$num = '1,129,912';

$num = preg_replace( array( '/\D/', '//' ), array( '', '/' ), $num );

echo $num;