Archive

Posts Tagged ‘number’

PHP Function To Work Out Factorial Numbers

October 8th, 2008 No comments

Factorial of a number is defined as the product of the number and all of the numbers small than it. So if you take the number 4 the factorial of that number is 24 or 1 x 2 x 3 x 4.

Factorials are useful for a number of applications, for example when working out how many times a set of objects can be combined in different ways.

Use the following PHP function to work out the factorial of any given number. The first thing it does it make sure that the number is greater than 1 because the factorial of the number 1 is 1.

function factorial($number){
 $result = 1;
 if($number > 1){
  for($i = 2; $i >= $number; $i++){
   $result *= $i;
  }
 }
 return $result;
}

The function works by using the *= operator, which does a calculation between the left and right sides (in this case multiplication) and stores the result on the left hand side. This operator is much like the += operator, and works in the same way.

An alternative of this is the GMP function gmp_fact(). GMP is a set of maths functions that can be used to do some special things like add very large numbers together. It has been part of the PHP core since version 4.0.4.

Beware that factorial numbers can get very large, very quickly. For example, the factorial of the number 50 is 30,414,093,201,713,375,576,366,966,406,747,986,832,057,064,836,514,787,179,557,289,984.

Categories: PHP Tags: , , , , ,

Get Fibonacci Numbers Using PHP

October 7th, 2008 No comments

Fibonacci numbers not only have a few uses, but are also quite a nice little number sequence in themselves.

The sequence starts at 0, the next number is 1, and every number after that is the sum of the last two numbers. So the third number is 1, and the second number is 2.

To create this number sequence in PHP we need to create the first two items in the array. As we know that these are 0 and 1 we can create the array like this.

$fibarray = array(0,1);

To create the third number we just add the first two numbers together.

$fibarray[2] = $fibarray[0]+$fibarray[1];

This can be continued for as much as we want if we add it to a loop.

for($i=0;$i<=10;++$i){
 $fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
}

This will create an array with the following values.


Array
(
 [0] => 0
 [1] => 1
 [2] => 1
 [3] => 2
 [4] => 3
 [5] => 5
 [6] => 8
 [7] => 13
 [8] => 21
 [9] => 34
 [10] => 55
)

Following on from this we can get a Fibonacci sequence to any position we want by using the following function.

function fibonacciSequence($pos){
 $fibarray = array(0,1);
 for($i=0;$i<=$pos;++$i){
  $fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
 }
 return $fibarray;
}

We can also create a very similar function that will only return a number at a particular position.

function fibonacciSequence($pos){
 $fibarray = array(0,1);
 for($i=0;$i<=$pos;++$i){
  $fibarray[$i] = $fibarray[$i-1] + $fibarray[$i-2];
 }
 return $fibarray[$pos];
}

For example, if we pass this function the number 56, the result would be 225,851,433,717.

Categories: PHP Tags: , , , , ,

Create Ordinal Numbers With PHP

August 11th, 2008 No comments

An ordinal number is just a way of saying that position the number is in. So for the number 1 the ordinal version of this is 1st. 2 is 2nd, 3 is 3rd and so on.

The following function will work out what ordinal text should be placed behind a number. This will be one of 'st', 'nd', 'rd' and 'th'.

function getOrdinal($number){
 // get first digit
 $digit = abs($number) % 10;
 $ext = 'th';
 // if the last two digits are between 4 and 21 add a th
 if(abs($number) %100 < 21 && abs($number) %100 > 4){
  $ext = 'th';
 }else{
  if($digit < 4){
   $ext = 'rd';
  }
  if($digit < 3){
   $ext = 'nd';
  }
  if($digit < 2){
   $ext = 'st';
  }
  if($digit < 1){
   $ext = 'th';
  }
 }
 return $number.$ext;
}

This set of if statements can be shortened by using the ternary control structure.

function getOrdinal($number){
 // get first digit
 $digit = abs($number) % 10;
 $ext = 'th';
$ext = ((abs($number) %100 < 21 && abs($number) %100 > 4) ? 'th' : (($digit < 4) ? ($digit < 3) ? ($digit < 2) ? ($digit < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
 return $number.$ext;
}

This is a little be harder to read, but it takes up less space and there is little need to change it unless you want to change the language.

Here is an example of the code in action.

echo getOrdinal(1);//1st
echo getOrdinal(2);//2nd
echo getOrdinal(3);//3rd
echo getOrdinal(4);//4th
echo getOrdinal(11);//11th
echo getOrdinal(87654311);//87654311th

Categories: PHP Tags: , , , , , , ,

Format Numbers With Commas In JavaScript

July 31st, 2008 No comments

I found a good function that details how to format numbers with commas in JavaScript and thought I would reproduce it here. It basically takes any number and turns it into formatted string with the thousands separated by commas. The number_format() function is available in PHP and I have been relying on PHP to sort out the formatting before returning it via an AJAX call. I can now include this function into my JavaScript library and do this on the client side.

The function works by using regular expressions to first split the string into whole number and decimal, before splitting the number by groups of three digits.

The regular expression used is (\d+)(\d{3}), which looks for a sequence of three numbers preceded by any numbers. This is a little trick that causes the regular expression engine to work from right to left, instead of left to right.

function addCommas(nStr){
 nStr += '';
 x = nStr.split('.');
 x1 = x[0];
 x2 = x.length > 1 ? '.' + x[1] : '';
 var rgx = /(\d+)(\d{3})/;
 while (rgx.test(x1)) {
  x1 = x1.replace(rgx, '$1' + ',' + '$2');
 }
 return x1 + x2;
}

This causes a comma to be added to every third numeric character. So for the number 123456 the string 123,456 is returned. Here are some more examples.

addCommas(1000); // 1,000
addCommas(12345); // 12,345
addCommas(1234567890); // 1,234,567,890
addCommas(12345.1234); // 12,345.1234

The site also details the creation of formatted numbers with the inclusion of different parameters. This means that instead of using a comma to separate block of three numbers you can use anything.

function addSeparatorsNF(nStr, inD, outD, sep){
 nStr += '';
 var dpos = nStr.indexOf(inD);
 var nStrEnd = '';
 if (dpos != -1) {
  nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
  nStr = nStr.substring(0, dpos);
 }
 var rgx = /(\d+)(\d{3})/;
 while (rgx.test(nStr)) {
  nStr = nStr.replace(rgx, '$1' + sep + '$2');
 }
 return nStr + nStrEnd;
}

This function was created because not every number is formatted in the same way. For example, the number 1234 might be formatted as 1,234 or even 1.234.

The function takes the following arguments

  • nStr : This is the number to be formatted. This might be a number or a string. No validation is done on this input.
  • inD : This is the decimal character for the string. This is usually a dot but might be something else.
  • outD : This is what to change the decimal character into.
  • sep : This is the separator, which is usually a comma.

The function takes the input string and splits it into two parts based on the decimal point character. The same regular expression is used on the string before the decimal point as in the previous function, the major difference is that the separator is taken from the function arguments.

Here are a few examples.

alert(addSeparatorsNF(1234567890,'.','.',',')); // 1,234,567,890
alert(addSeparatorsNF(12345.1234,'.','POINT','COMMA')); // 12COMMA345POINT1234
alert(addSeparatorsNF(12345.1234,'5','POINT','COMMA')); // 1COMMA234POINT.1234
alert(addSeparatorsNF('1234,56',',','.',',')); // 1,234.56

Printing Out File And Class Information In PHP

July 18th, 2008 No comments

If you are debugging a PHP application then you might want more information than the values of some current variables. There are a number of built in magic variables that can be used to print out the file name, line number, class and method that the debug statement is printed out on. Here is an example that prints out some information from a class.

class class_test{
 
function method_test(){
  // the full path to the current file
  print 'File: '.__FILE__.'<br />';
 
  // print the current line
  print 'Line: '.__LINE__.'<br />';
 
  // print the current class name
  print 'class: '.__CLASS__.'<br />';
 
  // print the current method name
  print 'method: '.__METHOD__.'<br />';
 
  // directory separator of the current
  // system (windows = \ and linux = /)
  print 'Directory separator: '.DIRECTORY_SEPARATOR.'<br />';
 }
}
$test = new class_test();
$test->method_test();

This will print out something like the following.

File: C:\Apache Software Foundation\Apache2.2\htdocs\test.php
Line: 10
class: class_test
method: class_test::method_test
Directory separator: \

Categories: PHP Tags: , , , , ,