Related
I am new to PHP and want to generate unique 10 digits number for my SKU Number. I tried using a date with IP address and got a unique value first time. But after a refresh or saving product data I still have that same SKU number. Any Help?? My code is:
<?php
if(!empty($_POST)) {
.....my code......
}
else{
$stamp = date("Ymdhis");
$ip = $_SERVER['REMOTE_ADDR'];
$sku = "$stamp-$ip";
$sku = str_replace(".", "", "$sku");
$sku = str_replace("-", "", "$sku");
$sku = str_replace(":", "", "$sku");
$sku = substr($sku, 0,10);
}
?>
Why not use the date to create a 10 digit unique number? year (4) + month with leading zero (2) + day with leading zero (2) + seconds with leading zero (2) = 10 digits
<?php
echo date("Ymds");
?>
Yall overcomplicating.
Use an existing library like random_compat (This library can generate strong random numbers and cryptographically secure random numbers.).
https://github.com/ircmaxell/random_compat/blob/master/lib/random.php
Example (your case):
$random = new \PHP\Random(true);
echo $random->token(10, '0123456789');
Here's a quick random-string-generator I wrote:
function generateRandomString($alpha = true, $nums = true, $usetime = false, $string = '', $length = 120) {
$alpha = ($alpha == true) ? 'abcdefghijklmnopqrstuvwxyz' : '';
$nums = ($nums == true) ? '1234567890' : '';
if ($alpha == true || $nums == true || !empty($string)) {
if ($alpha == true) {
$alpha = $alpha;
$alpha .= strtoupper($alpha);
}
}
$randomstring = '';
$totallength = $length;
for ($na = 0; $na < $totallength; $na++) {
$var = (bool)rand(0,1);
if ($var == 1 && $alpha == true) {
$randomstring .= $alpha[(rand() % mb_strlen($alpha))];
} else {
$randomstring .= $nums[(rand() % mb_strlen($nums))];
}
}
if ($usetime == true) {
$randomstring = $randomstring.time();
}
return($randomstring);
} // end generateRandomString
You can use it like this for what you need:
$SKU = generateRandomString(false, true, false, '', 10);
you could use this $sku = rand(1000000000,9999999999) this php function will generate a random no. every time
I'm programming a script that inserts a text on an image, it works but not entirely, ie if a user adds a line break in the textarea is fine, but if all the text is on one line looks bad . This is my code
$str="this is a string inserted by an user";
$img_width= 500;
$img_height= 500;
$font_size = 1;
$txt_max_width = intval(0.6 * $img_width);
do {
$font_size++;
$p = imagettfbbox($font_size,0,$font,$str);
$txt_width=$p[2]-$p[0];
} while ($txt_width <= $txt_max_width);
$y = $img_height * 0.4;
$x = ($img_width - $txt_width) / 2;
$white = imagecolorallocate($img, 255, 255, 255);
imagettftext($img, $font_size, 0, $x, $y, $white, $font, $str);
imagepng($img);
imagedestroy($img);
Look at this for understand http://app.xskarx.com
PS: sorry for my bad english
What you want to do, is to split the string into smaller block or chunks, for that, you have chunk_split in PHP.
You will use it this way:
// initialize variables
$final_string = false;
$size_of_the_chunk = 20;
$str = "_this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string_";
$length_of_string = strlen( $str );
// work only if necessary
if ( $length_of_string > $size_of_the_chunk ) {
$final_string = chunk_split( $str, $size_of_the_chunk );
} else {
$final_string = $str;
}
The main problem you may have, is that the string will get split on random places, at least random from the perspective of the user, and so, the fragments may not make much sense. Try to improve the user interface by informing that they should use line breaks.
function ApplyLineBreaks(strTextAreaId) {
var oTextarea = document.getElementById(strTextAreaId);
if (oTextarea.wrap) {
oTextarea.setAttribute("wrap", "off");
}
else {
oTextarea.setAttribute("wrap", "off");
var newArea = oTextarea.cloneNode(true);
newArea.value = oTextarea.value;
oTextarea.parentNode.replaceChild(newArea, oTextarea);
oTextarea = newArea;
}
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
function testBreak(strTest) {
oTextarea.value = strTest;
return oTextarea.scrollWidth > nEmptyWidth;
}
function findNextBreakLength(strSource, nLeft, nRight) {
var nCurrent;
if(typeof(nLeft) == 'undefined') {
nLeft = 0;
nRight = -1;
nCurrent = 64;
}
else {
if (nRight == -1)
nCurrent = nLeft * 2;
else if (nRight - nLeft <= 1)
return Math.max(2, nRight);
else
nCurrent = nLeft + (nRight - nLeft) / 2;
}
var strTest = strSource.substr(0, nCurrent);
var bLonger = testBreak(strTest);
if(bLonger)
nRight = nCurrent;
else
{
if(nCurrent >= strSource.length)
return null;
nLeft = nCurrent;
}
return findNextBreakLength(strSource, nLeft, nRight);
}
var i = 0, j;
var strNewValue = "";
while (i < strRawValue.length) {
var breakOffset = findNextBreakLength(strRawValue.substr(i));
if (breakOffset === null) {
strNewValue += strRawValue.substr(i);
break;
}
var nLineLength = breakOffset - 1;
for (j = nLineLength - 1; j >= 0; j--) {
var curChar = strRawValue.charAt(i + j);
if (curChar == ' ' || curChar == '-' || curChar == '+') {
nLineLength = j + 1;
break;
}
}
strNewValue += strRawValue.substr(i, nLineLength) + "\n";
i += nLineLength;
}
oTextarea.value = strNewValue;
oTextarea.setAttribute("wrap", "");
}
This function accepts the ID of the textarea as its parameter and whenever there is word wrap, it pushes a new line break into the textarea. Run the function in the form submit and you will get the text with proper line breaks in the server side code.
This way the text will appear exactly as the user sees it before the image is made. There is no need for the user to guess how the lines will break.
This function was found within another answer: finding "line-breaks" in textarea that is word-wrapping ARABIC text
As designing a new platform we tried to integrate the IBAN numbers. We have to make sure that the IBAN is validated and the IBAN stored to the database is always correct. So what would be a proper way to validate the number?
As the logic was explained in my other question, I've created a function myself. Based on the logic explained in the Wikipedia article find a proper function below. Country specific validation.
Algorithm and character lengths per country at https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN.
function checkIBAN($iban)
{
if(strlen($iban) < 5) return false;
$iban = strtolower(str_replace(' ','',$iban));
$Countries = array('al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24);
$Chars = array('a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35);
if(array_key_exists(substr($iban,0,2), $Countries) && strlen($iban) == $Countries[substr($iban,0,2)]){
$MovedChar = substr($iban, 4).substr($iban,0,4);
$MovedCharArray = str_split($MovedChar);
$NewString = "";
foreach($MovedCharArray AS $key => $value){
if(!is_numeric($MovedCharArray[$key])){
if(!isset($Chars[$MovedCharArray[$key]])) return false;
$MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
}
$NewString .= $MovedCharArray[$key];
}
if(bcmod($NewString, '97') == 1)
{
return true;
}
}
return false;
}
Slight modification of #PeterFox answer including support for bcmod() when bcmath is not available,
<?php
function isValidIBAN ($iban) {
$iban = strtolower($iban);
$Countries = array(
'al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,'hr'=>21,'cy'=>28,'cz'=>24,
'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,
'is'=>26,'ie'=>22,'il'=>23,'it'=>27,'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,
'mt'=>31,'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24,'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,'pt'=>25,'qa'=>29,
'ro'=>24,'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24
);
$Chars = array(
'a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,'m'=>22,
'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,'y'=>34,'z'=>35
);
if (strlen($iban) != $Countries[ substr($iban,0,2) ]) { return false; }
$MovedChar = substr($iban, 4) . substr($iban,0,4);
$MovedCharArray = str_split($MovedChar);
$NewString = "";
foreach ($MovedCharArray as $k => $v) {
if ( !is_numeric($MovedCharArray[$k]) ) {
$MovedCharArray[$k] = $Chars[$MovedCharArray[$k]];
}
$NewString .= $MovedCharArray[$k];
}
if (function_exists("bcmod")) { return bcmod($NewString, '97') == 1; }
// http://au2.php.net/manual/en/function.bcmod.php#38474
$x = $NewString; $y = "97";
$take = 5; $mod = "";
do {
$a = (int)$mod . substr($x, 0, $take);
$x = substr($x, $take);
$mod = $a % $y;
}
while (strlen($x));
return (int)$mod == 1;
}
The accepted answer is not the preferred way of validation. The specification dictates the following:
Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid
Replace the two check digits by 00 (e.g. GB00 for the UK)
Move the four initial characters to the end of the string
Replace the letters in the string with digits, expanding the string as necessary, such that A or a = 10, B or b = 11, and Z or z = 35. Each alphabetic character is therefore replaced by 2 digits
Convert the string to an integer (i.e. ignore leading zeroes)
Calculate mod-97 of the new number, which results in the remainder
Subtract the remainder from 98, and use the result for the two check digits. If the result is a single digit number, pad it with a leading 0 to make a two-digit number
I've written a class that validates, formats and parses strings according to the spec. Hope this helps some save the time required to roll their own.
The code can be found on GitHub here.
top rated function does NOT work.
Just try a string with '%' in it...
I'm using this one :
function checkIBAN($iban) {
// Normalize input (remove spaces and make upcase)
$iban = strtoupper(str_replace(' ', '', $iban));
if (preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $iban)) {
$country = substr($iban, 0, 2);
$check = intval(substr($iban, 2, 2));
$account = substr($iban, 4);
// To numeric representation
$search = range('A','Z');
foreach (range(10,35) as $tmp)
$replace[]=strval($tmp);
$numstr=str_replace($search, $replace, $account.$country.'00');
// Calculate checksum
$checksum = intval(substr($numstr, 0, 1));
for ($pos = 1; $pos < strlen($numstr); $pos++) {
$checksum *= 10;
$checksum += intval(substr($numstr, $pos,1));
$checksum %= 97;
}
return ((98-$checksum) == $check);
} else
return false;
}
I found this solution in cakephp 3.7 validation class. Plain beautiful php realization.
/**
* Check that the input value has a valid International Bank Account Number IBAN syntax
* Requirements are uppercase, no whitespaces, max length 34, country code and checksum exist at right spots,
* body matches against checksum via Mod97-10 algorithm
*
* #param string $check The value to check
*
* #return bool Success
*/
public static function iban($check)
{
if (!preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $check)) {
return false;
}
$country = substr($check, 0, 2);
$checkInt = intval(substr($check, 2, 2));
$account = substr($check, 4);
$search = range('A', 'Z');
$replace = [];
foreach (range(10, 35) as $tmp) {
$replace[] = strval($tmp);
}
$numStr = str_replace($search, $replace, $account . $country . '00');
$checksum = intval(substr($numStr, 0, 1));
$numStrLength = strlen($numStr);
for ($pos = 1; $pos < $numStrLength; $pos++) {
$checksum *= 10;
$checksum += intval(substr($numStr, $pos, 1));
$checksum %= 97;
}
return ((98 - $checksum) === $checkInt);
}
This function check the IBAN and need GMP activate http://php.net/manual/en/book.gmp.php.
function checkIban($string){
$to_check = substr($string, 4).substr($string, 0,4);
$converted = '';
for ($i = 0; $i < strlen($to_check); $i++){
$char = strtoupper($to_check[$i]);
if(preg_match('/[0-9A-Z]/',$char)){
if(!preg_match('/\d/',$char)){
$char = ord($char)-55;
}
$converted .= $char;
}
}
// prevent: "gmp_mod() $num1 is not an integer string" error
$converted = ltrim($converted, '0');
return strlen($converted) && gmp_strval(gmp_mod($converted, '97')) == 1;
}
enjoy !
I have a question about formatting the Rupee currency (Indian Rupee - INR).
For example, numbers here are represented as:
1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
Refer Indian Numbering System
I have to do with it PHP.
I have saw this question Displaying Currency in Indian Numbering Format. But couldn't able to get it for PHP my problem.
Update:
How to use money_format() in indian currency format?
You have so many options but money_format can do the trick for you.
Example:
$amount = '100000';
setlocale(LC_MONETARY, 'en_IN');
$amount = money_format('%!i', $amount);
echo $amount;
Output:
1,00,000.00
Note:
The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.
Pure PHP Implementation - Works on any system:
$amount = '10000034000';
$amount = moneyFormatIndia( $amount );
echo $amount;
function moneyFormatIndia($num) {
$explrestunits = "" ;
if(strlen($num)>3) {
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++) {
// creates each of the 2's group and adds a comma to the end
if($i==0) {
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
} else {
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash; // writes the final format where $currency is the currency symbol.
}
$num = 1234567890.123;
$num = preg_replace("/(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/i", "$1,", $num);
echo $num;
// Input : 1234567890.123
// Output : 1,23,45,67,890.123
// Input : -1234567890.123
// Output : -1,23,45,67,890.123
echo 'Rs. '.IND_money_format(1234567890);
function IND_money_format($money){
$len = strlen($money);
$m = '';
$money = strrev($money);
for($i=0;$i<$len;$i++){
if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$len){
$m .=',';
}
$m .=$money[$i];
}
return strrev($m);
}
NOTE:: it is not tested on float values and it suitable for only Integer
The example you've linked is making use of the ICU libraries which are available with PHP in the intl ExtensionDocs:
$fmt = new NumberFormatter($locale = 'en_IN', NumberFormatter::CURRENCY);
echo $fmt->format(10000000000.1234)."\n"; # Rs 10,00,00,00,000.12
Or maybe better fitting in your case:
$fmt = new NumberFormatter($locale = 'en_IN', NumberFormatter::DECIMAL);
echo $fmt->format(10000000000)."\n"; # 10,00,00,00,000
Simply use below function to format in INR.
function amount_inr_format($amount) {
$fmt = new \NumberFormatter($locale = 'en_IN', NumberFormatter::DECIMAL);
return $fmt->format($amount);
}
Check this code, it works 100% for Indian Rupees format with decimal format.
You can use numbers like :
123456.789
123.456
123.4
123
and 1,2,3,4,5,6,7,8,9,.222
function moneyFormatIndia($num){
$explrestunits = "" ;
$num = preg_replace('/,+/', '', $num);
$words = explode(".", $num);
$des = "00";
if(count($words)<=2){
$num=$words[0];
if(count($words)>=2){$des=$words[1];}
if(strlen($des)<2){$des="$des";}else{$des=substr($des,0,2);}
}
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
// creates each of the 2's group and adds a comma to the end
if($i==0)
{
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
}else{
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return "$thecash.$des"; // writes the final format where $currency is the currency symbol.
}
When money_format is not available :
function format($amount): string
{
list ($number, $decimal) = explode('.', sprintf('%.2f', floatval($amount)));
$sign = $number < 0 ? '-' : '';
$number = abs($number);
for ($i = 3; $i < strlen($number); $i += 3)
{
$number = substr_replace($number, ',', -$i, 0);
}
return $sign . $number . '.' . $decimal;
}
<?php
$amount = '-100000.22222'; // output -1,00,000.22
//$amount = '0100000.22222'; // output 1,00,000.22
//$amount = '100000.22222'; // output 1,00,000.22
//$amount = '100000.'; // output 1,00,000.00
//$amount = '100000.2'; // output 1,00,000.20
//$amount = '100000.0'; // output 1,00,000.00
//$amount = '100000'; // output 1,00,000.00
echo $aaa = moneyFormatIndia($amount);
function moneyFormatIndia($amount)
{
$amount = round($amount,2);
$amountArray = explode('.', $amount);
if(count($amountArray)==1)
{
$int = $amountArray[0];
$des=00;
}
else {
$int = $amountArray[0];
$des=$amountArray[1];
}
if(strlen($des)==1)
{
$des=$des."0";
}
if($int>=0)
{
$int = numFormatIndia( $int );
$themoney = $int.".".$des;
}
else
{
$int=abs($int);
$int = numFormatIndia( $int );
$themoney= "-".$int.".".$des;
}
return $themoney;
}
function numFormatIndia($num)
{
$explrestunits = "";
if(strlen($num)>3)
{
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++) {
// creates each of the 2's group and adds a comma to the end
if($i==0) {
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
} else {
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash; // writes the final format where $currency is the currency symbol.
}
?>
So if I'm reading that right, the Indian Numbering System separates the thousands, then every power of a hundred past that? Hmm...
Perhaps something like this?
function indian_number_format($num) {
$num = "".$num;
if( strlen($num) < 4) return $num;
$tail = substr($num,-3);
$head = substr($num,0,-3);
$head = preg_replace("/\B(?=(?:\d{2})+(?!\d))/",",",$head);
return $head.",".$tail;
}
$amount=-3000000000111.11;
$amount<0?(($sign='-').($amount*=-1)):$sign=''; //Extracting sign from given amount
$pos=strpos($amount, '.'); //Identifying the decimal point position
$amt= substr($amount, $pos-3); // Extracting last 3 digits of integer part along with fractional part
$amount= substr($amount,0, $pos-3); //removing the extracted part from amount
for(;strlen($amount);$amount=substr($amount,0,-2)) // Now loop through each 2 digits of remaining integer part
$amt=substr ($amount,-2).','.$amt; //forming Indian Currency format by appending (,) for each 2 digits
echo $sign.$amt; //Appending sign
I think this a quick and simplest solution:-
function formatToInr($number){
$number=round($number,2);
// windows is not supported money_format
if(setlocale(LC_MONETARY, 'en_IN')){
return money_format('%!'.$decimal.'n', $number);
}
else {
if(floor($number) == $number) {
$append='.00';
}else{
$append='';
}
$number = preg_replace("/(\d+?)(?=(\d\d)+(\d)(?!\d))(\.\d+)?/i", "$1,", $number);
return $number.$append;
}
}
You should check the number_format function.Here is the link
Separating thousands with commas will look like
$rupias = number_format($number, 2, ',', ',');
I have used different format parameters to money_format() for my output.
setlocale(LC_MONETARY, 'en_IN');
if (ctype_digit($amount) ) {
// is whole number
// if not required any numbers after decimal use this format
$amount = money_format('%!.0n', $amount);
}
else {
// is not whole number
$amount = money_format('%!i', $amount);
}
//$amount=10043445.7887 outputs 1,00,43,445.79
//$amount=10043445 outputs 1,00,43,445
Above Function Not working with Decimal
$amount = 10000034000.001;
$amount = moneyFormatIndia( $amount );
echo $amount;
function moneyFormatIndia($num){
$nums = explode(".",$num);
if(count($nums)>2){
return "0";
}else{
if(count($nums)==1){
$nums[1]="00";
}
$num = $nums[0];
$explrestunits = "" ;
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3);
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits;
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
if($i==0)
{
$explrestunits .= (int)$expunit[$i].",";
}else{
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash.".".$nums[1];
}
}
Answer : 10,00,00,34,000.001
It's my very own function to do the task
function bd_money($num) {
$pre = NULL; $sep = array(); $app = '00';
$s=substr($num,0,1);
if ($s=='-') {$pre= '-';$num = substr($num,1);}
$num=explode('.',$num);
if (count($num)>1) $app=$num[1];
if (strlen($num[0])<4) return $pre . $num[0] . '.' . $app;
$th=substr($num[0],-3);
$hu=substr($num[0],0,-3);
while(strlen($hu)>0){$sep[]=substr($hu,-2); $hu=substr($hu,0,-2);}
return $pre.implode(',',array_reverse($sep)).','.$th.'.'.$app;
}
It took 0.0110 Seconds per THOUSAND query while number_format took 0.001 only.
Always try to use PHP native functions only when performance is target issue.
$r=explode('.',12345601.20);
$n = $r[0];
$len = strlen($n); //lenght of the no
$num = substr($n,$len-3,3); //get the last 3 digits
$n = $n/1000; //omit the last 3 digits already stored in $num
while($n > 0) //loop the process - further get digits 2 by 2
{
$len = strlen($n);
$num = substr($n,$len-2,2).",".$num;
$n = round($n/100);
}
echo "Rs.".$num.'.'.$r[1];
If you dont want to use any inbuilt function in my case i was doing on iis server so was unable to use one the function in php so did this
$num = -21324322.23;
moneyFormatIndiaPHP($num);
function moneyFormatIndiaPHP($num){
//converting it to string
$numToString = (string)$num;
//take care of decimal values
$change = explode('.', $numToString);
//taking care of minus sign
$checkifminus = explode('-', $change[0]);
//if minus then change the value as per
$change[0] = (count($checkifminus) > 1)? $checkifminus[1] : $checkifminus[0];
//store the minus sign for further
$min_sgn = '';
$min_sgn = (count($checkifminus) > 1)?'-':'';
//catch the last three
$lastThree = substr($change[0], strlen($change[0])-3);
//catch the other three
$ExlastThree = substr($change[0], 0 ,strlen($change[0])-3);
//check whethr empty
if($ExlastThree != '')
$lastThree = ',' . $lastThree;
//replace through regex
$res = preg_replace("/\B(?=(\d{2})+(?!\d))/",",",$ExlastThree);
//main container num
$lst = '';
if(isset($change[1]) == ''){
$lst = $min_sgn.$res.$lastThree;
}else{
$lst = $min_sgn.$res.$lastThree.".".$change[1];
}
//special case if equals to 2 then
if(strlen($change[0]) === 2){
$lst = str_replace(",","",$lst);
}
return $lst;
}
This for both integer and float values
function indian_money_format($number)
{
if(strstr($number,"-"))
{
$number = str_replace("-","",$number);
$negative = "-";
}
$split_number = #explode(".",$number);
$rupee = $split_number[0];
$paise = #$split_number[1];
if(#strlen($rupee)>3)
{
$hundreds = substr($rupee,strlen($rupee)-3);
$thousands_in_reverse = strrev(substr($rupee,0,strlen($rupee)-3));
$thousands = '';
for($i=0; $i<(strlen($thousands_in_reverse)); $i=$i+2)
{
$thousands .= $thousands_in_reverse[$i].$thousands_in_reverse[$i+1].",";
}
$thousands = strrev(trim($thousands,","));
$formatted_rupee = $thousands.",".$hundreds;
}
else
{
$formatted_rupee = $rupee;
}
if((int)$paise>0)
{
$formatted_paise = ".".substr($paise,0,2);
}else{
$formatted_paise = '.00';
}
return $negative.$formatted_rupee.$formatted_paise;
}
Use this function:
function addCommaToRs($amt, &$ret, $dec='', $sign=''){
if(preg_match("/-/",$amt)){
$amts=explode('-',$amt);
$amt=$amts['1'];
static $sign='-';
}
if(preg_match("/\./",$amt)){
$amts=explode('.',$amt);
$amt=$amts['0'];
$l=strlen($amt);
static $dec;
$dec=$amts['1'];
} else {
$l=strlen($amt);
}
if($l>3){
if($l%2==0){
$ret.= substr($amt,0,1);
$ret.= ",";
addCommaToRs(substr($amt,1,$l),$ret,$dec);
} else{
$ret.=substr($amt,0,2);
$ret.= ",";
addCommaToRs(substr($amt,2,$l),$ret,$dec);
}
} else {
$ret.= $amt;
if($dec) $ret.=".".$dec;
}
return $sign.$ret;
}
Call it like this:
$amt = '';
echo addCommaToRs(123456789.123,&$amt,0);
This will return 12,34,567.123.
<?php
function moneyFormatIndia($num)
{
//$num=123456789.00;
$result='';
$sum=explode('.',$num);
$after_dec=$sum[1];
$before_dec=$sum[0];
$result='.'.$after_dec;
$num=$before_dec;
$len=strlen($num);
if($len<=3)
{
$result=$num.$result;
}
else
{
if($len<=5)
{
$result='Rs '.substr($num, 0,$len-3).','.substr($num,$len-3).$result;
return $result;
}
else
{
$ls=strlen($num);
$result=substr($num, $ls-5,2).','.substr($num, $ls-3).$result;
$num=substr($num, 0,$ls-5);
while(strlen($num)!=0)
{
$result=','.$result;
$ls=strlen($num);
if($ls<=2)
{
$result='Rs. '.$num.$result;
return $result;
}
else
{
$result=substr($num, $ls-2).$result;
$num=substr($num, 0,$ls-2);
}
}
}
}
}
?>
heres is simple thing u can do ,
float amount = 100000;
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
String moneyString = formatter.format(amount);
System.out.println(moneyString);
The output will be , Rs.100,000.00 .
declare #Price decimal(26,7)
Set #Price=1234456677
select FORMAT(#Price, 'c', 'en-In')
Result:
1,23,44,56,677.00
Does anybody know a PHP function for IMEI validation?
Short solution
You can use this (witchcraft!) solution, and simply check the string length:
function is_luhn($n) {
$str = '';
foreach (str_split(strrev((string) $n)) as $i => $d) {
$str .= $i %2 !== 0 ? $d * 2 : $d;
}
return array_sum(str_split($str)) % 10 === 0;
}
function is_imei($n){
return is_luhn($n) && strlen($n) == 15;
}
Detailed solution
Here's my original function that explains each step:
function is_imei($imei){
// Should be 15 digits
if(strlen($imei) != 15 || !ctype_digit($imei))
return false;
// Get digits
$digits = str_split($imei);
// Remove last digit, and store it
$imei_last = array_pop($digits);
// Create log
$log = array();
// Loop through digits
foreach($digits as $key => $n){
// If key is odd, then count is even
if($key & 1){
// Get double digits
$double = str_split($n * 2);
// Sum double digits
$n = array_sum($double);
}
// Append log
$log[] = $n;
}
// Sum log & multiply by 9
$sum = array_sum($log) * 9;
// Compare the last digit with $imei_last
return substr($sum, -1) == $imei_last;
}
Maybe can help you :
This IMEI number is something like this: ABCDEF-GH-IJKLMNO-X (without “-” characters)
For example: 350077523237513
In our example ABCDEF-GH-IJKLMNO-X:
AB is Reporting Body Identifier such as 35 = “British Approvals Board of Telecommunications (BABT)”
ABCDEF is Type Approval Code
GH is Final Assembly Code
IJKLMNO is Serial Number
X is Check Digit
Also this can help you : http://en.wikipedia.org/wiki/IMEI#Check_digit_computation
If i don't misunderstood, IMEI numbers using Luhn algorithm . So you can google this :) Or you can search IMEI algorithm
Maybe your good with the imei validator in the comments here:
http://www.php.net/manual/en/function.ctype-digit.php#77718
But I haven't tested it
Check this solution
<?php
function validate_imei($imei)
{
if (!preg_match('/^[0-9]{15}$/', $imei)) return false;
$sum = 0;
for ($i = 0; $i < 14; $i++)
{
$num = $imei[$i];
if (($i % 2) != 0)
{
$num = $imei[$i] * 2;
if ($num > 9)
{
$num = (string) $num;
$num = $num[0] + $num[1];
}
}
$sum += $num;
}
if ((($sum + $imei[14]) % 10) != 0) return false;
return true;
}
$imei = '868932036356090';
var_dump(validate_imei($imei));
?>
IMEI validation uses Luhn check algorithm. I found a link to a page where you can validate your IMEI. Furthermore, at the bottom of this page is a piece of code written in JavaScript to show how to calculate the 15th digit of IMEI and to valid IMEI. I might give you some ideas. You can check it out here http://imei.sms.eu.sk/index.html
Here is a jQuery solution which may be of use: https://github.com/madeinstefano/imei-validator
good fun from kasperhartwich
function validateImei($imei, $use_checksum = true) {
if (is_string($imei)) {
if (ereg('^[0-9]{15}$', $imei)) {
if (!$use_checksum) return true;
for ($i = 0, $sum = 0; $i < 14; $i++) {
$tmp = $imei[$i] * (($i%2) + 1 );
$sum += ($tmp%10) + intval($tmp/10);
}
return (((10 - ($sum%10)) %10) == $imei[14]);
}
}
return false;
}