I want to put comma in every 3 digit for a number, for example.
$number = 1234567;
// should print 1,234,567
how can I do this?
update: please see this code
<?php
/**
* Get Popularity Text of a Domain via Alexa XML Data
*
* #return string|FALSE text or FALSE on error
*/
function alexa_get_rank($domain)
{
$alexa = "http://data.alexa.com/data?cli=10&dat=s&url=%s";
$request_url = sprintf($alexa, urlencode($domain));
$xml = simplexml_load_file($request_url);
if (!$xml) {
return FALSE;
}
$nodeAttributes = $xml->SD[1]->POPULARITY->attributes();
$text = (int) $nodeAttributes['TEXT'];
$num = number_format($text);
return $num;
}
in this return only 3 digit.
Use
echo number_format('1234567');
PHP Manual : number_format()
Try this one:
$number = 1234567;
echo number_format($number);
Use this as ref.
$number = 123456789;
$number = number_format($number);
echo $number;
See number_format.
<?php
echo number_format(1234567890); //1,234,567,890
$num = 1234567.65;
$num = number_format($num);
echo $num; // $num = 1,234,568
<?
$number = 1234567;
echo number_format($number); // this returns : 1,234,567
?>
Learn more about number_format();
$number = 1234.56;
//english notation (default)
$english_format_number = number_format($number);// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');// 1 234,56
//----------------------------------------------
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');// 1234.57
Check out number_format() at php.net for more information.
To format numbers, one can use number_format
Try this code:
$number=1234567;
$number_format=number_format($number,0,".",","); // return 1,234,567
Related
How can I show and hide the some numbers of a phone number by replacing it with * like 0935***3256 by PHP?
EX:
09350943256 -> 0935***3256 09119822432 -> 0911***2432
09215421597 -> 0921***1597...
$number = '09350943256';
echo str_pad(substr($number, -4), strlen($number), '*', STR_PAD_LEFT);
Top php code result is as: *******3256 but i want result as: 0935***3256
How is it?
You could use substr and concat this way
to work for any $number with any number of n digit length
<?php
$number = "112222";
$middle_string ="";
$length = strlen($number);
if( $length < 3 ){
echo $length == 1 ? "*" : "*". substr($number, - 1);
}
else{
$part_size = floor( $length / 3 ) ;
$middle_part_size = $length - ( $part_size * 2 );
for( $i=0; $i < $middle_part_size ; $i ++ ){
$middle_string .= "*";
}
echo substr($number, 0, $part_size ) . $middle_string . substr($number, - $part_size );
}
The output if you make $number = "1" is * and if $number = "12" is *2 and for $number = "112222" is 11**22. and it goes on.
In short:
$phone = 01133597084;
$maskedPhone = substr($phone, 0, 4) . "****" . substr($phone, 7, 4);
// Output: 0113****7084
You can use substr_replace() function
<?php
$mobnum ="09350943256";
for($i=4;$i<7;$i++)
{
$mobnum = substr_replace($mobnum,"*",$i,1);
}
echo $mobnum;
?>
You can use substr() to fetch the first 4 and last 4, and add four * in the middle manually, and put it all together in a string.
$phone = "09350943256";
$result = substr($phone, 0, 4);
$result .= "****";
$result .= substr($phone, 7, 4);
echo $result;
The above would output
0935****3256
Live demo
<?php
$phone='05325225990';
function stars($phone)
{
$times=strlen(trim(substr($phone,4,5)));
$star='';
for ($i=0; $i <$times ; $i++) {
$star.='*';
}
return $star;
}
$result=str_replace(substr($phone, 4,5), stars($phone), $phone);
echo $result;
?>
0532*****90
Instead of doing the math of calculating indices, I suggest this „declarative“ solution:
<?php
$number='0123456789';
$matches=[];
preg_match('/(\\d{4})(\\d+)(\\d{4})/', $number, $matches);
$result=$matches[1].str_repeat('*',strlen($matches[2])).$matches[2];
print($result);
?>
I need a function to check if number have 2 decimals or not.
For example:
$number = '1.00'; // Valid
$number2 = '1'; // Not valid
$number3 = '1.000' //Not valid
You can check it like that:
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
You would have to convert your variable to a String, but this is not a big problem. Do it like that:
$d = 100.0/81.0;
$s = strval($d);
You can do something like this:
if(strlen(substr(strrchr($number, "."), 1)) == 2){
echo "valid";
}else{
echo "not valid";
}
Regex could be a solution since your numbers seem to be declared as strings.
Code :
<?php
$re = "/(\d\.\d{2})(?!\d)/";
$array_input = array('1.00', '1', '1.000');
foreach($array_input as $row)
{
if(preg_match($re, $row, $matches) == 0)
echo $row . " isn't a valid value with 2 decimals only. <br>";
else
echo $row . " is valid. <br>";
}
?>
Output :
1.00 is valid.
1 isn't a valid value with 2 decimals only.
1.000 isn't a valid value with 2 decimals only.
Why would you not just force them to have 2 decimals using something like this
$original = 2;
$float = number_format($number, 2);
// echo $float = 2.00
I guess if you need to enforce that a float only has 2 decimals you could do something like the following.
$numbers = array(2.453, 3.35, 2.53, 1.636);
foreach($numbers as $number) {
if(strpos($number, '.') !== false) {
if(strlen($parts[1]) == 2) {
echo $number .' is valid!';
} else {
echo $number .' is NOT valid!';
}
}
}
The above is one way to accomplish this but there are many others. You could use array_map or array_filter and you could also use math such as the following
$numbers = array(2.453, 3.35, 2.53, 1.636);
$valid_numbers = array_filter($numbers, function($number) { return strlen($number) - strpos($number, '.');
function check_decimals($input, $number_of_decimals)
{
if(strlen(substr(strrchr((string)$input, "."), 1)) == $number_of_decimals)
{
return TRUE;
}
else {
return FALSE;
}
}
check_decimals("1.000", 2);
This may be a solution using preg_match_all
$re = "/^\\d+(?:\\.\\d{2})?$/m";
$str = "1.00\n13333.55\n1.000";
preg_match_all($re, $str, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
REGEX: https://regex101.com/r/nB7eC4/1
CODE: http://codepad.viper-7.com/49ZuEa
I want to remove last digit from decimal number in PHP.
Lets say I have 14.153. I want it to be 14.15. I will do this step till my number is no longer decimal.
I think this should work:
<?php
$num = 14.153;
$strnum = (string)$num;
$parts = explode('.', $num);
// $parts[0] = 14;
// $parts[1] = 153;
$decimalPoints = strlen($parts[1]);
// $decimalPoints = 3
if($decimalPoints > 0)
{
for($i=0 ; $i<=$decimalPoints ; $i++)
{
// substring($strnum, 0, 0); causes an empty result so we want to avoid it
if($i > 0)
{
echo substr($strnum, 0, '-'.$i).'<br>';
}
else
{
echo $strnum.'<br>';
}
}
}
?>
echo round(14.153, 2); // 14.15
The round second parameter sets the number of digits.
You can try this.
Live DEMO
<?php
$number = 14.153;
echo number_format($number,2);
I have a value, lets say its 1000.
Now I have to generate a random minus or plus percentage of 1000.
In particular I have to generate or a -20% of 1000 or a +20% of 1000 randomly.
I tried using rand() and abs() but with no success..
Is there a way in PHP to achieve the above?
A bit of basic mathematics
$number = 1000;
$below = -20;
$above = 20;
$random = mt_rand(
(integer) $number - ($number * (abs($below) / 100)),
(integer) $number + ($number * ($above / 100))
);
rand(0, 1) seems to work fine for me. Maybe you should make sure your percentage is in decimal format.
<?php
$val = 10000;
$pc = 0.2;
$result = $val * $pc;
if(rand(0, 1)) echo $result; else echo -$result;
if(rand(0, 1)) echo $result; else echo -$result;
if(rand(0, 1)) echo $result; else echo -$result;
if(rand(0, 1)) echo $result; else echo -$result;
if(rand(0, 1)) echo $result; else echo -$result;
?>
$number = 10000;
$percent = $number*0.20;
$result = (rand(0,$percent)*(rand(0,1)*2-1));
echo $result;
Or if you want some sort of running balance type thing....
function plusminus($bank){
$percent = $bank*0.20;
$random = (rand(0,$percent)*(rand(0,1)*2-1));
return $bank + $random;
}
$new = plusminus(10000);
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
echo $new."<br>";
$new = plusminus($new);
I know this is really old now but stumbled across it looking for something similar where I needed a random sign (+ or -) so opted for a random boolean:
<?php $sign = (rand(0,1) == 1) ? '+' : '-'; ?>
Thanks to this this answer.
So I would opt for a solution like this:
<?php
// Alter these as needed
$number = 1000;
$percentage = 20;
// Calculate the change
$change_by = $number * ($percentage / 100);
// Set a boolean at random
$random_boolean = rand(0,1) == 1;
// Calculate the result where we are using plus if true or minus if false
$result = ($random_boolean) ? $number + $change_by : $number - $change_by;
// Will output either 1200 or 800 using these numbers as an example
echo $result;
?>
What is the best way to add dashes to a phone number in PHP? I have a number in the format xxxxxxxxxx and I want it to be in the format xxx-xxx-xxxx. This only applies to 10 digit US phone numbers.
$number = "1234567890";
$formatted_number = preg_replace("/^(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $number);
EDIT: To be a bit more generic and normalize a US phone number given in any of a variety of formats (which should be common practice - there's no reason to force people to type in a phone number in a specific format, since all you're interested in are the digits and you can simply discard the rest):
function localize_us_number($phone) {
$numbers_only = preg_replace("/[^\d]/", "", $phone);
return preg_replace("/^1?(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $numbers_only);
}
echo localize_us_number("5551234567"), "\n";
echo localize_us_number("15551234567"), "\n";
echo localize_us_number("+15551234567"), "\n";
echo localize_us_number("(555) 123-4567"), "\n";
echo localize_us_number("+1 (555) 123-4567"), "\n";
echo localize_us_number("Phone: 555 1234567 or something"), "\n";
$number = '1234567890';
if(ctype_digit($number) && strlen($number) == 10) {
$number = substr($number, 0, 3) .'-'.
substr($number, 3, 3) .'-'.
substr($number, 6);
}
Or if you for some reason want to avoid substr:
$number = '1234567890';
if(ctype_digit($number) && strlen($number) == 10) {
$parts = str_split($number, 3);
$number = $parts[0] .'-'. $parts[1] .'-'. $parts[3].$parts[4];
}
iterate through the string and make counter. When counter is 3 or 7 insert dash.
I feel obliged to post. Cheesiest solution:
$number = "1234567890";
$formatted_number = "$number[0]$number[1]$number[2]-$number[3]$number[4]$number[5]-$number[6]$number[7]$number[8]$number[9]";
But it works and its fast. vs. the preg_replace solution:
250,000 iterations:
preg_replace: 1.23 seconds
ugly solution: 0.866 seconds
Pretty meaningless but fun :P
Here's what I used. It's not perfect, but it's an improvement over #Thilo's answer. It checks for a leading 1. If it's there, it ignores it. The code also ignores separating dashes, commas, and spaces, so it will work with 1231231234, 123 123 1234, and 123.123.1234. It doesn't handle numbers with parenthesis, but I'm sure there's another thread out there with that solution!
$formatted_number = preg_replace("/^1?(?:[- .])?(\d{3})(?:[- .])?(\d{3})(?:[- .])?(\d{4})$/", "($1) $2-$3", $not_formatted_phone_number);
A modification of Thilo's answer providing complete conditional formatting control over the leading "1".
public function phoneFormat($number) {
$numbersOnly = preg_replace("/[^\d]/", "", $number);
$nums = array_filter(explode("-", preg_replace("/^(1|)(\d{3})(\d{3})(\d{4})$/",
"$1-$2-$3-$4", $numbersOnly)));
$output = $numbersOnly;
if(count($nums) == 3){
$output = "($nums[1])-$nums[2]-$nums[3]";
}elseif(count($nums) == 4){
$output = "$nums[0]-($nums[1])-$nums[2]-$nums[3]";
}
return $output;
}
Here's what I came up with:
function format_phone($var_num) {
$var_num = trim($var_num);
$var_num = str_replace("(","",$var_num);
$var_num = str_replace(")","",$var_num);
$var_num = str_replace("-","",$var_num);
$var_num = str_replace(" ","",$var_num);
$var_num = str_replace(".","",$var_num);
$var_num = substr($var_num, -10);
$var_area_code = substr($var_num, 0, -7);
$var_exchange = substr($var_num, 3, -4);
$var_extention = substr($var_num, -4);
$var_return = "{$var_area_code}-{$var_exchange}-{$var_extention}";
return $var_return;
}
// Examples:
$phone_number = "1 (757) 555-1212";
// $phone_number = "17575551212";
// $phone_number = "(757) 555-1212";
// $phone_number = "757.555.1212";
echo "{$phone_number} = " . format_phone($phone_number);