Source Source - 2 months ago 7
PHP Question

adding characters in a string multiple times

I want to separate numbers by a space, in sets of 4. e.g. 1234567890, would become 1234 5678 90

I managed to create a script to achieve this, but it seems over the top, is there any easier way of achieving this?

$num = 23853267362365;
$count = strlen($num)/4;

$new_num = array();
for ($x = 1; $x <= $count; $x++) {
$num_len = strlen($num);
if($num_len>4) {
$new_num[] = substr($num,0,4);
$num = substr($num,4,$num_len-4);
}
}

$num = implode(' ',$new_num);

Answer

chunk_split():

echo chunk_split(1234567890, 4, ' ');

Link: http://php.net/manual/function.chunk-split.php