mangosaft
mangosaft

Reputation: 31

How I can space the number with PHP command?

I want to code the PHP for spacing the number, example:

$number = "55375911";

So this number should to space to 2-digit and 6-digit, it shows so: "55 3759 11". How I can code this?

Thank you for helping.

Upvotes: 0

Views: 682

Answers (3)

Roland Ruul
Roland Ruul

Reputation: 1242

You could also use substring (if the number is always the same length):

$number = "55375911";
$number_f = substr($number, 0, 2) . " " . substr($number, 2, 4) . " " . substr($number, 6, 6);

echo $number_f; // "55 3759 11"

Upvotes: 6

I am assuming that the OP wants code for equally spaced numbers for a given number string and the specified digits. The number is give is $number in the code below and $digit is the number of digits each group should have.

$number = "455375911";
$length = strlen($number);
$digit = 3;
$curlen = $length;
$cur = "";
echo $number . "<br />";
$last = $length%$digit;
echo "curlen $curlen<br />last " . $last . "<br />";

while($curlen >= $digit){
   $curlen = $curlen - $digit;
   $cur = substr($number, $curlen, $digit) . (empty($cur)?"":" ") . $cur;

   echo "curlen " . $curlen . "<br />";
}
if ($last){
   $cur = substr($number, 0, $last) . (empty($cur)?"":" ") . $cur;
}
else if ($curlen){
  $cur = substr($number, 0, $digit) . (empty($cur)?"":" ") . $cur;
}
echo $cur;

Upvotes: 1

pr1nc3
pr1nc3

Reputation: 8338

<?php

$number = "55375911";
$number = str_split($number, 2);
$number=$number[0].' '.$number[1].''.$number[2].' '.$number[3];
echo $number;

This code will work for you for this kind of numbers.

The output is :

55 3759 11

Upvotes: 1

Related Questions