Математические функции

Содержание

  • abs — Модуль числа
  • acos — Арккосинус
  • acosh — Гиперболический арккосинус
  • asin — Арксинус
  • asinh — Гиперболический арксинус
  • atan2 — Арктангенс двух переменных
  • atan — Арктангенс
  • atanh — Гиперболический арктангенс
  • base_convert — Преобразование числа между произвольными системами счисления
  • bindec — Двоичное в десятичное
  • ceil — Округляет дробь в большую сторону
  • cos — Косинус
  • cosh — Гиперболический косинус
  • decbin — Переводит число из десятичной системы счисления в двоичную
  • dechex — Переводит число из десятичной системы счисления в шестнадцатиричную
  • decoct — Переводит число из десятичной системы счисления в восьмеричную
  • deg2rad — Преобразует значение из градусов в радианы
  • exp — Вычисляет число e в степени
  • expm1 — Возвращает exp(number) - 1, рассчитанное таким образом, что результат точен, даже если number близок к нулю.
  • floor — Округляет дробь в меньшую сторону
  • fmod — Возвращает дробный остаток от деления по модулю
  • getrandmax — Вовзращает максимально возможное случайное число
  • hexdec — Переводит число из шестнадцатиричной системы счисления в десятичную
  • hypot — Рассчитывает длину гипотенузы прямоугольного треугольника
  • is_finite — Проверяет, является ли значение допустимым конечным числом
  • is_infinite — Проверяет, является ли значение бесконечным
  • is_nan — Проверяет, является ли значение "не числом"
  • lcg_value — Комбинированный линейно конгруэнтный генератор
  • log10 — Десятичный логарифм
  • log1p — Возвращает log(1 + number), рассчитанный таким, что результат точен, даже если значение number близко к нулю
  • log — Натуральный логарифм
  • max — Возвращает наибольшее значение
  • min — Находит наименьшее значение
  • mt_getrandmax — Показывает максимально возможное значение случайного числа
  • mt_rand — Генерирует случайное значение методом mt
  • mt_srand — Переинициализирует генератор случайных чисел mt
  • octdec — Переводит число из восьмеричной системы счисления в десятичную
  • pi — Возвращает число Пи
  • pow — Возведение в степень
  • rad2deg — Преобразует значение из радианов в градусы
  • rand — Генерирует случайное число
  • round — Округляет число типа float
  • sin — Синус
  • sinh — Гиперболический синус
  • sqrt — Квадратный корень
  • srand — Изменяет начальное число генератора псевдослучайных чисел
  • tan — Тангенс
  • tanh — Гиперболический тангенс

Коментарии

Автор:
for those looking for a credit card verification function i wrote a simple LUHN Formula algorithm:

<?php
$valid 
1;

$numOfDigits strlen($ccNumber);

$i = -1;
while (
$i>=$numOfDigits){
  if ((
$i 2) == 0){
   
$double 2*(substr($ccNumber$i1));
   
$total += substr($double,0,1);
    if (
strlen($double 1)){
     
$total += substr($double,1,1);
    }
  } else {
   
$total += substr($ccNumber$i1);
  }
 
$i--;
}

if ((
$total 10) != 0){
 
$valid 0;
}
?>
2001-02-19 17:43:02
http://php5.kiev.ua/manual/ru/ref.math.html
Автор:
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

function n_pick_r($n,$r){$n=(int)$n; $r=(int)$r;return (fact($n)/fact($n-$r));}
function n_choose_r($n,$r){$n=(int)$n; $r=(int)$r;return (n_pick_r($n,$r)/fact($r));}

Hope that helps someone!
2002-05-31 18:54:02
http://php5.kiev.ua/manual/ru/ref.math.html
The example for Factorials given above is wrong. Here a correct version, so that you do not have to reinvent the wheel again...

<?php
function mathFact$s )
{
 
$r = (int) $s;

  if ( 
$r )
   
$r 1;
  else {
    for ( 
$i $r-1$i 1$i-- )
     
$r $r $i;
  }

  return( 
$r );
}
?>
2002-08-05 12:08:05
http://php5.kiev.ua/manual/ru/ref.math.html
I was looking for a truncate function. Not finding one, I wrote my own. Since it deals with everything as a number, I imagine it's faster than the alternative of using string functions. HTH...

<?php
function truncate ($num$digits 0) {

   
//provide the real number, and the number of 
    //digits right of the decimal you want to keep.

   
$shift pow(10$digits);
    return ((
floor($num $shift)) / $shift);
}
?>
2002-11-08 15:15:03
http://php5.kiev.ua/manual/ru/ref.math.html
This code will convert a decimal to it's fraction equivalent. The precision can be set by changing PRECISION.

<?php
define
(PRECISION.01);

$count=0;
$result=array();
decimalToFraction($_REQUEST['dec'],$count,&$result);
$count count($result);
$simp_fract simplifyFraction($result,$count,1,$result[$count]);

echo 
$simpl_fract;

// Start of functions

/*
   Converts a decimal to unsimplified fraction represented in an array
*/
function decimalToFraction($decimal,$count,$result) {
   
$a = (1/$decimal);
   
$b = ( $a floor($a)  );
   
$count++;
    if (
$b .01 && $count <= 5decimalToFraction($b,$count,&$result);
   
$result[$count] = floor($a);
}

/* 
    Simplifies a fraction in an array form that is returned from 
    decimalToFraction
*/
function simplifyFraction($fraction,$count,$top,$bottom) {
   
$next $fraction[$count-1];
   
$a = ($bottom $next) + $top;
   
$top $bottom;
   
$bottom $a;
   
$count--;
    if (
$count 0simplifyFraction($fraction,$count,$top,$bottom);
    else {
        return 
"<font size=1>$bottom/$top</font>";
    }
}
?>
2002-12-08 16:58:00
http://php5.kiev.ua/manual/ru/ref.math.html
Theres another faster way of doing even/odd number checking by using bitwise operators. Don't ask me how it works, I just found this out by experimenting with it (could the editor possibly explain?)

if ((1&$num)) {
 echo "$num is odd";
}

if (!(1&$num)) {
 echo "$num is even";
}

How it works is (1&$num) returns a 1 for odd numbers and returns 0 when it's an even number.
2003-02-22 10:04:18
http://php5.kiev.ua/manual/ru/ref.math.html
Here is how to calculate standard deviation in PHP where $samples is an array of incrementing numeric keys and the values are your samples:

$sample_count = count($samples);

for ($current_sample = 0; $sample_count > $current_sample; ++$current_sample) $sample_square[$current_sample] = pow($samples[$current_sample], 2);

$standard_deviation = sqrt(array_sum($sample_square) / $sample_count - pow((array_sum($samples) / $sample_count), 2));
2003-04-16 14:10:41
http://php5.kiev.ua/manual/ru/ref.math.html
The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0. 

So if you do a " 1 & $num", it will return zero if the number is even (since xxxxxxx0 [the even number in binary] and 00000001 [the 1]) don't share any bits, and will return 1 if the number is odd (xxxxxx1 and 000001).

a clever way of doing things, but $num % 2 would work as well i think :).
2003-08-27 11:07:24
http://php5.kiev.ua/manual/ru/ref.math.html
here is an algorithm to calculate gcd of a number. This is Euclid algorithm i was studying in Maths. I've converted it in php for the fun.

<?php
 
if($a && $b)
  { 
$ax=$a$bx=$b;
   
$r=fmod($a,$b);
  if(!
$r){$rx=$r;}
   while(
$r){
   
$rx=$r;
   
$a=$b;
   
$b=$r;
   
$r=fmod($a,$b);
    }
   }
echo 
'PGCD ('.$ax.' , '.$bx.' ) = '.$rx;
?>
2003-09-30 18:46:13
http://php5.kiev.ua/manual/ru/ref.math.html
Here's yet another greatest common denominator (gcd) function, a reeeeally small one.

function gcd($n,$m){
if(!$m)return$n;return gcd($m,$n%$m);
}

It works by recursion. Not really sure about it's speed, but it's really small! This won't work on floating point numbers accurately though. If you want a floating point one, you need to have at least PHP 4, and the code would be

function gcd($n,$m){
if(!$m)return$n;return gcd($m,fmod($n,$m));
}
2003-10-05 07:00:46
http://php5.kiev.ua/manual/ru/ref.math.html
Here are are a nPr and a nPc function
(had to define NaN - don't know, how to this the "rigth" way)

<?php
define 
(NaN,acos(1.01));

function 
nCr($n,$r){
   if (
$r $n)
      return 
NaN;
   if ((
$n-$r) < $r)
      return 
nCr($n,($n-$r));
   
$return 1;
   for (
$i=0;$i $r;$i++){
     
$return *= ($n-$i)/($i+1);
   }
   return 
$return;
}

function 
nPr($n,$r){
   if (
$r $n)
      return 
NaN;
   if (
$r)
      return 
$n*(nPr($n-1,$r-1));
   else
      return 
1;
}
?>
2004-01-13 15:47:57
http://php5.kiev.ua/manual/ru/ref.math.html
Please note that shorter is not always better
(meaning that really short faculty implementation above).

In my opinion, a clearer way to code this is, including a check
for negative or non-integer values.

In order to calculate the faculty of a positive integer,
an iterative way (which might be harder to understand)
is usually a bit faster, but I am using it only for small
values so it is not really important to me:

<?php

   
// Calculate the Faculty of a positive int-value
   
function iFaculty($a_iFac)
    {
      if (
$a_iFac 0)
      { 
          return 
$a_iFac $this->iFaculty($a_iFac 1);
      }
      elseif (
$a_iFac == 0)
      { 
          return 
1;
      }
      else
      {
          return 
0// Wrong argument!
     
}
    } 
?>

I've also written another function to calculate the
binomial coefficient of 2 values, I didn't find it anywhere yet so I hope it might help someone (works fine with the above stated faculty-function and ready to be used inside of your own classes!)

<?php

   
// calculates the binomial coefficient "n over k" of 2 positive int values
    // for n >= k
   
function iBinCoeff($a_iN$a_iK)
    {
       
// the binomial coefficient is defined as n! / [ (n-k)! * k! ]
       
return $this->iFaculty($a_iN) / ($this->iFaculty($a_iN $a_iK) * $this->iFaculty($a_iK));   
    } 

?>
2004-04-28 17:48:36
http://php5.kiev.ua/manual/ru/ref.math.html
For people interest in Differential Equations, I've done a function that receive a string like: x^2+x^3 and put it in
2x+3x^2 witch is the differantial of the previous equation.

In the code there is one thing missing: the $string{$i} is often going outOfBound (Uninitialized string offset: 6 in...)
if your error setting is set a little too high... I just dont know how to fix this.

So there is the code for differential equation with (+ and -) only:

<?
function differentiel($equa)
{
   
$equa strtolower($equa);
    echo 
"Equation de depart: ".$equa."<br>";
   
$final ""
   
    for(
$i 0$i strlen($equa); $i++)
    {
       
//Make a new string from the receive $equa
       
if($equa{$i} == "x" && $equa{$i+1} == "^")
        {
           
$final .= $equa{$i+2};
           
$final .= "x^";
           
$final .= $equa{$i+2}-1;
        }
        elseif(
$equa{$i} == "+" || $equa{$i} == "-")
        {
           
$final .= $equa{$i};
        }
        elseif(
is_numeric($equa{$i}) && $i == 0)
        {
           
//gerer parenthese et autre terme generaux + gerer ^apres: 2^2
           
$final .= $equa{$i}."*";
        }
        elseif(
is_numeric($equa{$i}) && $i && $equa{$i-1} != "^")
        {
           
//gerer ^apres: 2^2
           
$final .= $equa{$i}."*";
        }
        elseif(
$equa{$i} == "^")
        {
            continue;
        }
        elseif(
is_numeric($equa{$i}) && $equa{$i-1} == "^")
        {
            continue;
        }
        else
        {
            if(
$equa{$i} == "x")
            {
               
$final .= 1;
            }
            else
            {
               
$final .= $equa{$i}; 
            }
        }
    }
   
//
    //Manage multiplication add in the previous string $final
    //
   
$finalMul "";
    for(
$i 0$i strlen($final); $i++)
    {
        if(
is_numeric($final{$i}) && $final{$i+1} == "*" && is_numeric($final{$i+2}))
        {
           
$finalMul .= $final{$i}*$final{$i+2};
        }
        elseif(
$final{$i} == "*")
        {
            continue;
        }
        elseif(
is_numeric($final{$i}) && $final{$i+1} != "*" && $final{$i-1} == "*")
        {
            continue;
        }
        else
        {
           
$finalMul .= $final{$i};   
        }
    }
    echo 
"equa final: ".$finalMul;
}
?>

I know this is not optimal but i've done this quick :)
If you guys have any comment just email me.
I also want to do this fonction In C to add to phpCore maybe soon...
Patoff
2004-06-08 22:36:45
http://php5.kiev.ua/manual/ru/ref.math.html
Occasionally a user must enter a number in a form. This function converts fractions to decimals and leaves decimals untouched. Of course, you may wish to round the final output, but that is not included here.

<?php
/*Some example values of $q
$q = "2.5";
$q = "2 1/2";
$q = "5/2";
*/
function Deci_Con($q){
//check for a space, signifying a whole number with a fraction
   
if(strstr($q' ')){
       
$wa strrev($q);
       
$wb strrev(strstr($wa' '));
       
$whole true;//this is a whole number
   
}
//now check the fraction part
   
if(strstr($q'/')){
        if(
$whole==true){//if whole number, then remove the whole number and space from the calculations
             
$q strstr($q' ');
        }
$b str_replace("/","",strstr($q'/'));//this is the divisor
//isolate the numerator
$c strrev($q);
$d strstr($c'/');
$e strrev($d);
$a str_replace("/","",$e);//the pre-final numerator
       
if($whole==true){//add the whole number to the calculations
           
$a $a+($wb*$b);//new numerator is whole number multiplied by denominator plus original numerator   
       
}
$q $a/$b;//this is now your decimal
return $q;
    }else{
        return 
$q;//not a fraction, just return the decimal
   
}
}
?>
2004-09-25 12:05:57
http://php5.kiev.ua/manual/ru/ref.math.html
If you need to deal with polar co-ordinates for somereason you will need to convert to and from x,y for input and output in most situations: here are some functions to convert cartesian to polar and polar to cartesian
<?
//returns array of r, theta in the range of 0-2*pi (in radians)
function rect2polar($x,$y)
{
     if(
is_numeric($x)&&is_numeric($y))
    {
       
$r=sqrt(pow($x,2)+pow($y,2));
        if(
$x==0)
        {
             if(
$y>0$theta=pi()/2;
            else 
$theta=3*pi()/2;
        }
        else if(
$x<0$theta=atan($y/$x)+pi();
        else if(
$y<0$theta=atan($y/$x)+2*pi();
        else 
$theta=atan($y/$x);
       
$polar=array("r"=>$r,"theta"=>$theta);
        return 
$polar;
    }
    else return 
false;
}

//r must be in radians, returns array of x,y
function polar2rect($r,$theta)
{
 if(
is_numeric($r)&&is_numeric($theta))
 {
       
$x=$r*cos($theta);
   
$y=$r*sin($theta);
   
$rect=array("x"=>$x,"y"=>$y);
 }
 else
 {
   return 
false;
 }
}
?>
2004-11-17 06:34:45
http://php5.kiev.ua/manual/ru/ref.math.html
Two functions I didn't find elsewhere... one to compute mean of an array of numbers, and another to computer variance of a sample of numbers. Both take an array of numbers as arguments. Not much error checking, or optimization...

(note: variance function uses the average function...)

<?php

function average($arr)
{
    if (!
count($arr)) return 0;

   
$sum 0;
    for (
$i 0$i count($arr); $i++)
    {
       
$sum += $arr[$i];
    }

    return 
$sum count($arr);
}

function 
variance($arr)
{
    if (!
count($arr)) return 0;

   
$mean average($arr);

   
$sos 0;    // Sum of squares
   
for ($i 0$i count($arr); $i++)
    {
       
$sos += ($arr[$i] - $mean) * ($arr[$i] - $mean);
    }

    return 
$sos / (count($arr)-1);  // denominator = n-1; i.e. estimating based on sample 
                                    // n-1 is also what MS Excel takes by default in the
                                    // VAR function
}

echo 
variance(array(4,6,23,15,18)); // echoes 64.7...correct value :)

?>
2005-01-06 16:32:20
http://php5.kiev.ua/manual/ru/ref.math.html
while joogat's one line function is short, it is probably better to calculate factorial iteratively instead of recursively. keep in mind if you want large factorials, you'll need to use some sort of arbitrary precision integer or perhaps the BCMath functions. then again, unless you're trying to do large numbers (170! is the highest that you can do that does not return infinity) you probably won't notice any time difference.
<?php
function factorial($in) {
   
// 0! = 1! = 1
   
$out 1;

   
// Only if $in is >= 2
   
for ($i 2$i <= $in$i++) {
       
$out *= $i;
    }

    return 
$out;
}
?>
2005-02-19 14:42:39
http://php5.kiev.ua/manual/ru/ref.math.html
thearbitcouncil at gmail dot com, you could just use array_sum():
<?php
function average($arr)
{
   if (!
is_array($arr)) return false;

   return 
array_sum($arr)/count($arr);
}

$array = array(51015);
echo 
average($array); // 10
?>
2005-07-26 19:57:27
http://php5.kiev.ua/manual/ru/ref.math.html
This is an efficient method of calculating the binomial coefficient C(n,k). This code was derived from Owant: Mastering Algorithms with Perl.

<?php
   
// calculate binomial coefficient
   
function binomial_coeff($n$k) {

     
$j $res 1;

      if(
$k || $k $n)
         return 
0;
      if((
$n $k) < $k)
         
$k $n $k;

      while(
$j <= $k) {
         
$res *= $n--;
         
$res /= $j++;
      }

      return 
$res;

   }
?>

If you compiled php with --enable-bcmath, you can get full integer values of extremely large numbers by replacing:

$res *= $n--;
$res /= $j++;

with:

$res = bcmul($res, $n--);
$res = bcdiv($res, $j++);
2005-10-18 09:37:30
http://php5.kiev.ua/manual/ru/ref.math.html
If you're an aviator and needs to calculate windcorrection angles and groundspeed (e.g. during flightplanning) this can be very useful.

$windcorrection = rad2deg(asin((($windspeed * (sin(deg2rad($tt - ($winddirection-180))))/$tas))));
$groundspeed = $tas*cos(deg2rad($windcorrection)) + $windspeed*cos(deg2rad($tt-($winddirection-180)));

You can probably write these lines more beautiful, but they work!
2005-12-01 12:01:46
http://php5.kiev.ua/manual/ru/ref.math.html
I needed to approximate an integral because i was not able to calculate it, so i wrote this function. It approximates an integral with the composite Simpson's rule.
More information on Simpson's rule: http://en.wikipedia.org/wiki/Simpson%27s_rule

<?php

function simpsonf($x){
// returns f(x) for integral approximation with composite Simpson's rule
   
return(pow((1+pow($x, (-4))), 0.5));
}
function 
simpsonsrule($a$b$n){
// approximates integral_a_b f(x) dx with composite Simpson's rule with $n intervals
// $n has to be an even number
// f(x) is defined in "function simpsonf($x)"
   
if($n%2==0){
     
$h=($b-$a)/$n;
     
$S=simpsonf($a)+simpsonf($b);
     
$i=1;
      while(
$i <= ($n-1)){
         
$xi=$a+$h*$i;
         if(
$i%2==0){
           
$S=$S+2*simpsonf($xi);
         }
         else{
           
$S=$S+4*simpsonf($xi);
         }
         
$i++;
      }
      return(
$h/3*$S);
      }
   else{
      return(
'$n has to be an even number');
   }
}

?>
2006-02-01 17:16:59
http://php5.kiev.ua/manual/ru/ref.math.html
Автор:
A function that simulates the sum operator. (http://en.wikipedia.org/wiki/Sum). Be careful with the expression because it may cause a security hole; note the single quotes to don't parse the "$".
<?php
# @param    string    $expr    expression to evaluate (for example (2*$x)^2+1)
# @param    string    $var      dummy variable (for example "x")
# @param    integer    $start
# @param    integer    $end
# @param    integer    $step

function sum($expr,$var,$start,$end,$step 1) {
   
$expr str_replace(';','',$expr);
   
$var str_replace('$','',$var);
   
$start = (int)$start;    $end = (int)$end;    $step = (int)$step;    $sum 0;
   
    for (
$i $start$i <= $end$i $i $step) {
       
$_expr str_replace('$'.$var,$i,$expr);   
       
$_eval '$_result = '.$_expr.'; return $_result;';
       
$_result = eval($_eval);
        if(
$result === FALSE) return "SYNTAX ERROR : $expr";
       
$sum += $_result;
    }
    return (int)
$sum;
}
?>
2006-03-03 15:36:33
http://php5.kiev.ua/manual/ru/ref.math.html
I think, this is the optimal code for calculating factorials:

<?php
function fact($int){
    if(
$int<2)return 1;
    for(
$f=2;$int-1>1;$f*=$int--);
    return 
$f;
};
?>

And another one for calculating the $int-th Fibonacci-number:

<?php
function fib($int){
    static 
$fibTable=array();
    return empty(
$fibTable[$int])?$fibTable[$int] = $int>1?fib($int-2)+fib($int-1):1:$fibTable[$int];
};
?>
2006-05-10 04:15:36
http://php5.kiev.ua/manual/ru/ref.math.html
I could not resist to do a simpler version of the ordinal function:
<?php
function ordinal($num)
{
   
$num = (int)$num;
   
$digit substr($num, -11);
   
$ord "th";
    switch(
$digit)
    {
        case 
1$ord "st"; break;
        case 
2$ord "nd"; break;
        case 
3$ord "rd"; break;
    break;
    }
return 
$num.$ord;
}
?>
One could replace the typecast with

<?php
if($num===NULL or $num==="")
{return 
NULL;}
?>

to get an empty result instead of "0th" in case $num is empty too.
2006-06-08 08:23:15
http://php5.kiev.ua/manual/ru/ref.math.html
well just a note.. maybe i'm a bit stupid.. but remember to use pow() rather than the "^" sign for exponents.. as it took me 5 minutes to figure out why it wasn't working.
2006-07-19 21:24:11
http://php5.kiev.ua/manual/ru/ref.math.html
To add to what Cornelius had, I have written a function that will take an array of numbers and return the least common multiple of them:

function lcm_arr($items){
    //Input: An Array of numbers
    //Output: The LCM of the numbers
    while(2 <= count($items)){
        array_push($items, lcm(array_shift($items), array_shift($items)));
    }
    return reset($items);
}

//His Code below with $'s added for vars

function gcd($n, $m) {
   $n=abs($n); $m=abs($m);
   if ($n==0 and $m==0)
       return 1; //avoid infinite recursion
   if ($n==$m and $n>=1)
       return $n;
   return $m<$n?gcd($n-$m,$n):gcd($n,$m-$n);
}

function lcm($n, $m) {
   return $m * ($n/gcd($n,$m));
}
2006-11-06 15:36:18
http://php5.kiev.ua/manual/ru/ref.math.html
Here's a least common denominator (lcd) function:

$array = array(3,4,6,8,18,2);
   
    function lcd($array,$x) {
               
        $mod_sum = 0;
       
        for($int=1;$int < count($array);$int++) {               
            $modulus[$int] = ($array[0]*$x) % ($array[$int]);
            $mod_sum = $mod_sum + $modulus[$int];           
        }
             
        if (!$mod_sum) {
            echo "LCD: ".($array[0]*$x)."\n";
        }
           
        else {
            lcd($array,$x+1);
        }
       
    }

lcd($array,1);
2006-12-02 11:14:13
http://php5.kiev.ua/manual/ru/ref.math.html
Автор:
//had a mistake in last post, heres the corrected version

/*
Just a simple function to trim digits from the left side of an integer. TRIM DOWN TO 4-> (ie. 987654 => 7654)
*/

function trimInteger($targetNumber,$newLength) {

    $digits = pow(10,$newLength);

    $s = ($targetNumber/ $digits); //make the last X digits the                  decimal part

    $t = floor($targetNumber / $digits); //drop the last X digits (the decimal part)

    $h = $s - $t; //remove all  but the decimal part

    $newInteger = ($h*$digits); //make the everything after the decimal point the new number

    return $newInteger;
}
2008-01-09 21:23:33
http://php5.kiev.ua/manual/ru/ref.math.html
Автор:
Wouldn't the following function do the same but a lot easier than the one in the comment before?

function trimInteger($targetNumber,$newLength) {
    return $targetNumber%pow(10,$newLength); 
}
2008-02-02 09:24:56
http://php5.kiev.ua/manual/ru/ref.math.html
Another ordinal method, which does not involve utilizing date functions:

<?php
sprintf
"%d%s"$tarray_poparray_slicearray_merge( array( "th","st","nd","rd"), array_fill4,6,"th")), $t%101)));'
?>
2010-11-04 13:09:18
http://php5.kiev.ua/manual/ru/ref.math.html
Автор:
Here's a simple way way to convert a number to an ordinal number I created:

$i == the number to convert. Put this inside a for loop if you need to populate an array.

<?php
// change increment variable to ordinal number.
$n1 $i 100//first remove all but the last two digits

$n2 = ($n1 20 ? $$i 10//remove all but last digit unless the number is in the teens, which all should be 'th'

//$n is now used to determine the suffix.
$ord = ($n2==$i.'st' : ( ($n2==$i.'nd' : ($n2==$i.'rd' $i.'th') ) ) )
?>
2011-04-19 00:40:55
http://php5.kiev.ua/manual/ru/ref.math.html
Another simpler function to check a number with the luhn algorithm :

<?php
function luhn($num){
    if(!
$num)
        return 
false;
   
$num array_reverse(str_split($num));
   
$add 0;
    foreach(
$num as $k => $v){
        if(
$k%2)
           
$v $v*2;
       
$add += ($v >= 10 $v $v);
    }
    return (
$add%10 == 0);
}
?>

Don't know if foreach and arrays operations are faster than while and substr, but I feel it clearer.
2012-07-19 00:48:09
http://php5.kiev.ua/manual/ru/ref.math.html
Автор:
Lowest Common Denominator:
function lcd($num, $start) {
    while($num % $start != 0) {
        $start++;
    }
    return $start;
}
2015-03-28 03:47:31
http://php5.kiev.ua/manual/ru/ref.math.html
Автор:
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

function n_pick_r($n,$r){$n=(int)$n; $r=(int)$r;return (fact($n)/fact($n-$r));}
function n_choose_r($n,$r){$n=(int)$n; $r=(int)$r;return (n_pick_r($n,$r)/fact($r));}

Hope that helps someone!
exmple:https://vb.3dlat.com/
2018-02-02 20:44:57
http://php5.kiev.ua/manual/ru/ref.math.html
Ajay Singh Deol is commonly known as Sunny Deol which is a famous Indian Television actor and a Politician as well. Want to know about the info then you can check it in your browser such as Sunny Deol age where you can get about his complete information. 
For your information, Sunny Deol is the person who won the Filmfare award for the best actor
2021-03-06 08:17:18
http://php5.kiev.ua/manual/ru/ref.math.html

    Поддержать сайт на родительском проекте КГБ