November 6, 2012

Find ratio for any number of variables in php?

Question by neha thamman

I want to find ratio for any number of variables in php.

For example: 1:2 10:100:50
30:90:120:150

How can I get such rations?

Answer by Starx

One way would be convert the values to decimal values and covert them to fraction.

I found a function that will do this: [Source]

function decToFraction($float) {
    // 1/2, 1/4, 1/8, 1/16, 1/3 ,2/3, 3/4, 3/8, 5/8, 7/8, 3/16, 5/16, 7/16,
    // 9/16, 11/16, 13/16, 15/16
    $whole = floor ( $float );
    $decimal = $float - $whole;
    $leastCommonDenom = 48; // 16 * 3;
    $denominators = array (2, 3, 4, 8, 16, 24, 48 );
    $roundedDecimal = round ( $decimal * $leastCommonDenom ) / $leastCommonDenom;
    if ($roundedDecimal == 0)
        return $whole;
    if ($roundedDecimal == 1)
        return $whole + 1;
    foreach ( $denominators as $d ) {
        if ($roundedDecimal * $d == floor ( $roundedDecimal * $d )) {
            $denom = $d;
            break;
        }
    }
    return ($whole == 0 ? '' : $whole) . " " . ($roundedDecimal * $denom) . "/" . $denom;
}

Now

$total = 1 / 2;
echo decToFraction($total);

Or, you could use PEAR’s Math_Fraction [Source]

include "Math/Fraction.php";

$fr = new Math_Fraction(1,2); //Put your variable like this    

// print as a string
// output: 1/2
echo $fr->toString();

// print as float
// output: 0.5
echo $fr->toFloat();
October 27, 2012

Custom Number format and images in between

Question by Maarten Hartman

I’d like to format a number(stored as 10000.23, or 1.23) with php, , and place images between them, like the following.

10000,23

becomes

[img1]100[img2]00[img3]10

and

1,10

becomes

[img1]0[img2]1[img3]10

Anyone knows how to do this?

I tried several number formats but none of them allowed me to separate the last 4 digits into two pairs ( 00.00.00 )

Answer by Starx

Looks as if you want currency Format and replace the quotation marks with images. Here is a small function to add commas on the number.

function cFormat($number) {
    while (true) {
        $replaced = preg_replace('/(-?d+)(ddd)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}

Then, here is how to replace them with images.

$int = 10000.23;
$int = cFormat($int);

// After adding comma, use str_replace() to replace comma with images
$int = str_replace(",", "<img src="comma.jpg" />", $int);
$int = str_replace(".", "<img src="period.jpg" />", $int);
October 13, 2012

Check whether an input string contains number

Question by Udara S.S Liyanage

I want to check whether an input string contains number.

I am trying to validate an input field. I want it to contain only alphabet, not numbers.

Answer by Starx

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

While implementing

var val = $('yourinputelement').val();
if(isNumeric(val)) { alert('number'); } 
else { alert('not number'); }

Update: To check if a string has numbers in them, you can use regular expressions to do that

var matches = val.match(/d+/g);
if (matches != null) {
    alert('number');
}
May 28, 2012

PHP Currency Regular Expression

Question by Lee

I am trying to find a piece of regex to match a currency value.

I would like to match only numbers and 1 decimal point ie

Allowed

  • 10
  • 100
  • 100.00

Not Allowed

  • Alpha Characters
  • 100,00
  • +/- 100

I have search and tried quite a few without any luck.

Hope you can advise

Answer by The Pixel Developer

if (preg_match('/^[0-9]+(?:.[0-9]+)?$/im', $subject))
{
    # Successful match
}
else
{
    # Match attempt failed
}

Side note : If you want to restrict how many decimal places you want, you can do something like this :

/^[0-9]+(?:.[0-9]{1,3})?$/im

So

100.000

will match, whereas

100.0001

wont.

If you need any further help, post a comment.

PS If you can, use the number formatter posted above. Native functions are always better (and faster), otherwise this solution will serve you well.

Answer by Starx

How about this

if (preg_match('/^d+(.d{2})?$/', $subject))
{
   // correct currency format
} else {
  //invalid currency format
}
April 16, 2012

regex to allow decimals, but no commas

Question by Rookieatthis

I need a regex expression that allows decimals but no commas. Such as:
1200.00
or
50.00
or
40
or
1
The expression is used in a validation to make sure people put in a price as a number, but no commas. I currently have a regex that allows for commas, numbers, and decimals, but I cannot seem to get the commas out.

This is the current regex that I have which doesnt allow commas or decimals, but I want decimals in there

/^[0-9 ]+$/,

Thanks for your help.

Answer by npinti

Something like this should work: ^d+(.d{2})?$

This basically states the following:

  • ^d+: Start from the beginning of the string (^) and match one or more digits (d+).
  • (.d{2})?: Match a period character (.) followed by exactly 2 digits (d{2}). The question mark denotes that the value within the brackets can either exist or not, meaning that it will match either 1 or 0 instances of the pattern.
  • $: The string must end here.

Answer by Starx

To match the currency you can use this regex

^(?:[1-9]d+|d)(?:.dd)?$
April 1, 2012

How can I generate a number that never be the same again(repeated) PHP

Question by yeah its me

Possible Duplicate:
Algorithm for generating a random number

is posible to generate a random number that is never repeated??

Is there a solution in php? or codeIgniter?

for example if i need to generate a random never repeated id for every user, how can i be sure that no user will have the same id?

Answer by Starx

Clearly speaking, there is always a chance for a number since every form is generated from same algorithm generally.

The safest way would be to check you database to ensure that, if an id is already taken like:

$id = "1"; //Your id to check
$query = "SELECT * FROM table where id=?";
$result = mysql_query($query);
if(mysql_num_rows($result)) { 
  //the id is present
}

It will be better if you use mysqli instead

$id = "1"; //Your id to check
$query = "SELECT * FROM table where id=?";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_bind_param($stmt, "i", $id);
mysql_stmt_execute($stmt);
if(mysql_stmt_num_rows($stmt))
  //the id is present
}  
mysqli_stmt_close($stmt);
...

Please fill the form - I will response as fast as I can!