#array_pop()
Explore tagged Tumblr posts
ali7ali · 6 months ago
Text
PHP Arrays and Built-in Functions
In 𝗟𝗲𝘀𝘀𝗼𝗻 𝟭.𝟯: 𝗣𝗛𝗣 𝗔𝗿𝗿𝗮𝘆𝘀 𝗮𝗻𝗱 𝗕𝘂𝗶𝗹𝘁-𝗶𝗻 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 🚀 we explore one of PHP’s most powerful data structures—𝗮𝗿𝗿𝗮𝘆𝘀.This lesson covers:• Types of arrays: Indexed, Associative, and Multidimensional• Manipulating arrays using built-in functions like array_push(), array_pop(), and sort()• Practical examples to make data handling in PHP easier and more efficient📺 Watch the full video on YouTube:…
0 notes
learnwithamit · 1 year ago
Text
Most commonly used PHP functions ?
Most commonly used PHP functions include: echo(): Outputs one or more strings. print(): Outputs a string. strlen(): Returns the length of a string. substr(): Returns a part of a string. explode(): Splits a string by a specified string. implode(): Joins array elements with a string. array_push(): Pushes one or more elements onto the end of an array. array_pop(): Pops the element off the…
View On WordPress
0 notes
tinchicus · 2 years ago
Text
PHP / array_pop
Esta funcion nos extrae y elimina el ultimo elemento de un array, dando la posibilidad de poder almacenarlo en una variable tambien, espero les sea de utilidad!
Bienvenidos sean a este post, hoy veremos una funcion para los array. Esta funcion extrae el ultimo elemento de un array y eliminarlo del mismo, veamos su sintaxis: array_pop(array) En este caso simplemente le debemos pasar el array que procesaremos, vamos a aplicarlo en un ejemplo y para ello crearemos un nuevo archivo con el nombre de array.php y le agregaremos el siguiente…
Tumblr media
View On WordPress
0 notes
phptrainingtrickstips · 2 years ago
Text
Array manipulation in PHP
PHP Certification Course, Array manipulation in PHP involves performing various operations on arrays, such as adding or removing elements, sorting, searching, and restructuring. PHP offers a rich set of array functions to facilitate these tasks. Here are some common array manipulation techniques:
Creating Arrays: Arrays in PHP can be created using square brackets [] or the array() construct. For example:phpCopy code$numbers = [1, 2, 3, 4, 5]; $fruits = array('apple', 'banana', 'cherry');
Adding Elements: To add elements to an array, you can use the assignment operator = or the [] notation. For example:phpCopy code$numbers[] = 6; // Adds 6 to the end of the $numbers array array_push($fruits, 'date'); // Adds 'date' to the end of the $fruits array
Removing Elements: Elements can be removed using functions like unset() or array manipulation functions like array_pop() and array_shift(). For example:phpCopy codeunset($numbers[2]); // Removes the element at index 2 $removedFruit = array_shift($fruits); // Removes and returns the first element
Merging Arrays: Arrays can be combined using functions like array_merge() or the + operator. For example:phpCopy code$combinedArray = array_merge($numbers, $fruits); $mergedArray = $numbers + $fruits; // Note: Keys are preserved
Sorting Arrays: Arrays can be sorted using functions like sort(), rsort(), asort(), ksort(), etc., based on different criteria such as value or key. For example:phpCopy codesort($numbers); // Sorts the array in ascending order ksort($fruits); // Sorts the array by keys
Searching in Arrays: Functions like in_array() and array_search() can be used to search for elements in an array. For example:phpCopy code$found = in_array('banana', $fruits); // Checks if 'banana' is in the $fruits array $index = array_search('cherry', $fruits); // Returns the index of 'cherry' in $fruits
Filtering Arrays: Functions like array_filter() allow you to create a new array with elements that meet specific criteria. For example:phpCopy code$filteredNumbers = array_filter($numbers, function($num) { return $num % 2 == 0; // Filters even numbers });
Iterating Over Arrays: Looping constructs like foreach and for are commonly used to iterate through arrays and perform operations on each element.
These are just a few examples of array manipulation techniques in PHP. Understanding these functions and techniques allows developers to effectively work with and manipulate arrays in their applications.
0 notes
yourblogcoach1 · 4 years ago
Link
Check the most useful PHP functions like:
is_array($arr) in_array($search, $arr, $type) sizeof($arr) array_merge($arr1, $arr2) array_keys($arr) array_values($arr) array_push($arr, $val) array_pop($arr) . . . more
0 notes
listliy · 2 years ago
Link
PHP Array functions list with description, check variety of built-in functions for working with PHP arrays. The PHP array functions are part of the PHP core and there is no installation needed to use these functions. Some commonly used array functions in PHP are count(), array_push(), array_pop(), array_slice(), array_merge(), array_reverse() among others. The array functions […]
0 notes
blog-by-raika · 3 years ago
Text
【 PHP 】PHP8に入門してみた 113日目 PHPの基本 ( 組み込み関数 配列への追加や削除 )
【 PHP 】PHP8に入門してみた 113日目 PHPの基本 ( 組み込み関数 配列への追加や削除 )
PHP8技術者認定初級試験 が始まるようなので 試験に向けて (できるだけ)勉強しようと思います! 使用する書籍は独習PHP 第4版(山田 祥寛)|翔泳社の本 (shoeisha.co.jp) となります。 組み込み関数 配列への追加や削除あれこれ array_push, array_pop, array_shift, array_unshift関数 配列に対して要素の追加・削除を行う関数があります。 先頭に追加する場合はarray_unshift、先頭の要素を削除(というか取り出し)がarray_shiftになります。 末尾に追加はarray_push、末尾の要素を取り除く(というか取り出し)がarray_popになります。 <!DOCTYPE html> <html lang="ja"> <head>     <meta charset="UTF-8">     <meta…
Tumblr media
View On WordPress
0 notes
hunteroil456 · 4 years ago
Text
Array Pop Php
Tumblr media
Change Orientation. Privacy policy and Copyright 1999-2021.
Php Array Pop First Element
Php Remove Array Element
PHParray_pop() Function
Thearray_pop() function in PHP pops or removes the last element from the arrayshortening the array by one element.
Syntax
2
array_pop(array&$array)
The code above is neat and efficient (as I tested, it's about 20% faster than arrayslice + arraypop for an array with 10000 elements; and the reason is that arraykeylast is really fast). This way the last value will also be removed.
Definition and Usage. The arraypop function deletes the last element of an array.
Parameter
array(required)– This parameter represents the inputarray to get the value from.
Return
Thisfunction returns the value of the last element of the array. It returnsNULL if the specified array is empty or is not an array.
Errors/Exceptions
Tumblr media
This function produces an error of level E_WARNING if the specified array parameter is a non-array.
Example 1
2
4
6
8
10
12
14
<?php
$array=array('Blue','Orange','Red','Yellow');
print_r($array);
$pop_element=array_pop($array);
echo('nArray before the pop() function...nPopped element: ');
echo('n');
?>
Output
Php Array Pop First Element
Example 2
2
4
6
8
10
12
14
16
18
<?php
$contestent_array=(1=>'Reema',2=>'Harshit',3=>'Sapna');
var_export($contestent_array);
$lastKey=array_pop($contestent_array);
echo('nThe II runner up is ');
//removing the last element of the array
var_export(array_pop($contestent_array));
echo('nThe winner of the match is ');
?>
Output
2
4
6
8
10
Student Array:
1=>'Reema',
3=>'Sapna',
The II runner up is'Sapna'
The winner of the match is'Reema'
Example 3
2
4
6
8
10
12
<?php
$contestent_array=array(null);
var_export($contestent_array);
$lastKey=array_pop($contestent_array);
echo('nThe last key is ');
?>
Output
Php Remove Array Element
array_padarray_productLast updated: Tue, 19 Sep 2006
(PHP 4, PHP 5)
array_pop -- Pop the element off the end of array
Description
mixed array_pop ( array &array )
array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned. ='constant'>='parameter'>='parameter'>='parameter'>='function'>
Note: This function will reset() the array pointer after use.='type'>='function'>
='note'>
='methodname'>
Example 1. array_pop()='function'> example
After this, $stack will have only 3 elements: ='varname'>
and raspberry will be assigned to $fruit. ='varname'>='literal'>
See also array_push(), array_shift(), and array_unshift(). ='function'>='function'>='function'>
Tumblr media
0 notes
airman7com · 5 years ago
Text
Array Push, POP PHP – PHP Array Tutorial
Push and pop array in PHP. We will learn how to use the push array and pop array method in PHP.
In PHP, the array methods like array_push and array_pop are used to add or remove elements or items from the array.
In PHP, the array_push method can be used to add or insert one or more items or elements from the end of an array. and The array_pop () method can use to extract, delete and remove the…
View On WordPress
0 notes
jamesphprealestatescript · 5 years ago
Text
PHP Arrays #7: Using array push, pop, shift and unshift function
youtube
array_push pushes a value to the end of the array array_pop pops a value from the end of array array_shift removes the first value from array and array_unshift adds a value to the start of the key Nguồn:https://phprealestatescript.com/ Xem Thêm Bài Viết Khác:https://phprealestatescript.com/lap-trinh-php
Share Tweet Share
The post PHP Arrays #7: Using array push, pop, shift and unshift function appeared first on PHP Realestate Script.
from PHP Realestate Script https://ift.tt/2OnCD3E via IFTTT
0 notes
phprealestatescript · 5 years ago
Text
PHP Arrays #7: Using array push, pop, shift and unshift function
youtube
array_push pushes a value to the end of the array array_pop pops a value from the end of array array_shift removes the first value from array and array_unshift adds a value to the start of the key Nguồn:https://phprealestatescript.com/ Xem Thêm Bài Viết Khác:https://phprealestatescript.com/lap-trinh-php
Share Tweet Share
The post PHP Arrays #7: Using array push, pop, shift and unshift function appeared first on PHP Realestate Script.
from PHP Realestate Script https://ift.tt/2OnCD3E via IFTTT
0 notes
sourabhdubey007 · 6 years ago
Text
How to validate Email Address with domain name
These are the exact steps for using this:
Include/require class-validate-email.php into your application or web page.
Instantiate a new instance of the validate_email class.
Pass the email address to the validate_email::validate_by_domain() method.
<?php /** * Validates email addresses * * This class is used to validate email addresses using several different criteria. * * @version 1.0 * @author Sourabh dubey */ class validate_email { /** * Accepted domains * @access private * @var array */ private $accepted_domains;
/** * The class constructor * * This sets up the class */ public function __construct() { // Set the accepted domains property $this->accepted_domains = array( ‘unl.edu’, ‘uni.edu’ ); }
/** * Validate email address by domain * * Checks if the email address belongs to an accepted domain */ public function validate_by_domain($email_address) { // Get the domain from the email address $domain = $this->get_domain( trim( $email_address ) );
// Check if domain is accepted. Return return if so if ( in_array( $domain, $this->accepted_domains ) ) { return true; }
return false; }
/** * Get the domain * * Gets the domain from an email address */ private function get_domain($email_address) { // Check if a valid email address was submitted if ( ! $this->is_email( $email_address ) ) { return false; }
// Split the email address at the @ symbol $email_parts = explode( ‘@’, $email_address );
// Pop off everything after the @ symbol $domain = array_pop( $email_parts );
return $domain; }
/** * Check email address * * Checks if the submitted value is a valid email address */ private function is_email($email_address) { // Filter submitted value to see if it’s a proper email address if ( filter_var ( $email_address, FILTER_VALIDATE_EMAIL ) ) { return true; }
return false; } }
<?php require_once( dirname( __FILE__ ) . ‘/class-validate-email.php’ ); $validate_email = new validate_email; // Valid if ( $validate_email->validate_by_domain(‘[email protected] ‘) ) { echo ‘<p>This is valid!</p>’; } else { echo ‘<p>This is NOT valid!</p>’; } // Valid if ( $validate_email->validate_by_domain(‘[email protected]’) ) { echo ‘<p>This is valid!</p>’; } else { echo ‘<p>This is NOT valid!</p>’; } // Not valid if ( $validate_email->validate_by_domain(‘[email protected]’) ) { echo ‘<p>This is valid!</p>’; } else { echo ‘<p>This is NOT valid!</p>’; }
The post How to validate Email Address with domain name appeared first on The Coding Bus.
from WordPress https://ift.tt/2RVJALJ via IFTTT
0 notes
hayalolsam · 7 years ago
Photo
Tumblr media
Genişletilmiş Dizi Nesne Sınıfı <?php class genisletilmisDiziNesnesi extends ArrayObject { private $dizi; public function __construct(){ if (is_array(func_get_arg(0))) $this->dizi = func_get_arg(0); else $this->dizi = func_get_args(); parent::__construct($this->dizi); } public function each($callback){ $yineleyici = $this->getIterator(); while($yineleyici->valid()) { $callback($yineleyici->current()); $yineleyici->next(); } } public function haric(){ $args = func_get_args(); return array_values(array_diff($this->dizi,$args)); } public function ilk(){ return $this->dizi[0]; } public function sira($deger){ return array_search($deger,$this->dizi); } public function denetle(){ echo print_r($this->dizi, true); } public function son(){ return $this->dizi; } public function terscevir($uygula=false){ if(!$uygula){ return array_reverse($this->dizi); }else{ $dizi = array_reverse($this->dizi); $this->dizi = $dizi; parent::__construct($this->dizi); return $this->dizi; } } public function shift(){ $eleman = array_shift($this->dizi); parent::__construct($this->dizi); return $eleman; } public function pop(){ $eleman = array_pop($this->dizi); parent::__construct($this->dizi); return $eleman; } } function yazdir($deger){ echo $deger; } $dizi = new genisletilmisDiziNesnesi(); $dizi->each("yazdir"); echo "<br>"; print_r($dizi->haric(2,3,4)); $dizi->denetle(); echo $dizi->sira(5); echo "<br>"; print_r($dizi->terscevir()); print_r($dizi->terscevir(true)); echo $dizi->shift(); echo "<br>"; echo $dizi->pop(); echo "<br>"; echo $dizi->son(); echo "<br>"; echo $dizi->ilk(); ?>
0 notes
thelaitkor-blog · 7 years ago
Text
Some surprisingly most useful PHP functions must to be known
Talking about surprising and useful functions of PHP, there exist a number of technical functions apart from the basic ones which are usual and mostly known to all who claim to be knowing PHP in the most basic ways. These are the beneficiary that one can enjoy in PHP.
Like you could be liking implode() to join arrays together into a string. There are many more functions of such kinds that you can find more pleasant in PHP and which would be the part of further discussion.
Once you have found and used implode(), you may also love to know about explode() to do the exact opposite of your need. The two amazing functions alone are worth using in PHP Application Development, viz. date() and strtotime(). These can also be used in JavaScript-heavy apps (especially helpful in Node.JS)
Let’s consider some of the useful and various PHP functions:
fgetcsv() and fputcsv() — you can use this function constantly to get and put csv data in order.
glob() -“ it could be used for the return files that matches a pattern (e.g “/tmp/*.*”).
array_push(), array_pop(), array_shift(), array_unshift() — this function is usually used to add or remove elements from the either sides of an array.
array_reverse() — you can use this function for flipping the particular array around.
set_time_limit() — use of PHP via CLI all the time and updating the time limit(30) inside a loop assures that looping any amount of data could be done through manipulating.
spl_autoload_register() — it could prevent you from the nightmare of managing include() and require() statements, combining with PHP namespaces and some sort of code directory structure.
phpcredits() — used to print out credits.
mysql() — it is an undocumented mystery function, call it for yourself! eval() — it’s a gateway to realms of wonder
These are some most required functions other than asort
Tumblr media
These are some most required functions other than asort, ksort, arsort, print_r(), empty(), mail(), header(), etc. which are fairly helpful too. Most of the users are yet not aware about these amazing functions. Other than that,the magic methods _get and_set are incredibly useful.
The language in PHP comes with an integrated development server since PHP 5.4. Due to this competing innovation you don’t need to setup an Apache virtual host for developing your project, just enter into the folder in which your code is and type — php -S localhost : 8080.
The two old PHP functions strspn and strcspn are least known to the people. Basically they provide you with the option to search for characters in a string that are present or not in the other string. It is significant for parsing text without leading to split your strings in smaller pieces nor using regular expressions, helping you to write faster PHP parser. It could also be used for building fast e-mail message parser, HTML parser and filter classes.
ArrayAccess interface is another function which allows you to access class variables as an array, which could be henceforth used to construct smarter Hash objects with consistent functions instead of using the plethora of array_functions. It’s also useful to template in MVC systems where you simply use PHP as the templates as well. The use of Reflection in PHP will guide you in solving most of the problems. Here you can inspect your big applications easily and can find the particular class or function defined, number of arguments, namespaces and so on.
In case you find yourself stuck while making the best out of any of these functions, you can always count on the support team of Laitkor to come to your rescue.
Source - https://medium.com/@dakshmishra1517/some-surprisingly-most-useful-php-functions-must-to-be-known-39dc4ca4a144
0 notes
monikafe23-blog · 8 years ago
Text
unciones Matemáticas
Tabla de contenidos ¶
abs — Valor absoluto
acos — Arco coseno
acosh — Arco coseno hiperbólico
asin — Arco seno
asinh — Arco seno hiperbólico
atan2 — Arco tangente de dos variables
atan — Arco tangente
atanh — Arco tangente hiperbólica
base_convert — Convertir un número entre bases arbitrarias
bindec — Binario a decimal
ceil — Redondear fracciones hacia arriba
cos — Coseno
cosh — Coseno hiperbólico
decbin — Decimal a binario
dechex — Decimal a hexadecimal
decoct — Decimal a octal
deg2rad — Convierte el número en grados a su equivalente en radianes
exp — Calcula la exponencial de e
expm1 — Devuelve exp(numero)-1, calculado de tal forma que no pierde precisión incluso cuando el valor del numero se aproxima a cero.
floor — Redondear fracciones hacia abajo
fmod — Devuelve el resto en punto flotante (módulo) de la división de los argumentos
getrandmax — Mostrar el mayor valor aleatorio posible
hexdec — Hexadecimal a decimal
hypot — Calcula la longitud de la hipotenusa de un triángulo de ángulo recto
intdiv — División entera
is_finite — Encuentra si un valor es un número finito legal
is_infinite — Encuentra si un valor es infinito
is_nan — Encuentra si un valor no es un número
lcg_value — Generador lineal congruente combinado
log10 — Logaritmo en base 10
log1p — Devuelve log(1 + numero), calculado de tal forma que no pierde precisión incluso cuando el valor del numero se aproxima a cero.
log — Logaritmo natural
max — Encontrar el valor más alto
min — Encontrar el valor más bajo
mt_getrandmax — Mostrar el mayor valor aleatorio posible
mt_rand — Genera un mejor número entero aleatorio
mt_srand — Genera el mejor número aleatorio a partir de una semilla
octdec — Octal a decimal
pi — Obtener valor de pi
pow — Expresión exponencial
rad2deg — Convierte el número en radianes a su equivalente en grados
rand — Genera un número entero aleatorio
round — Redondea un float
sin — Seno
sinh — Seno hiperbólico
sqrt — Raíz cuadrada
srand — Genera un número aleatorio a partir de una semilla
tan — Tangente
tanh — Tangente hiperbólica
add a note
User Contributed Notes 50 notes
up
down
2
florian at shellfire dot de
13 years ago
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));        } ?>
up
down
1
pat.mat AT sympatico DOT com
13 years ago
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 > 0 && $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
up
down
1
webkid%webkid.com
15 years ago
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!
up
down
1
jbeardsl [found_at] gte [d0t] net
14 years ago
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); } ?>
up
down
0peter-stangl at t-online dot de
11 years ago
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');   } } ?>
up
down
0tmpa at yahoo dot com
12 years ago
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; } ?>
up
down
0thearbitcouncil at gmail dot com
12 years ago
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 :) ?>
up
down
0jl85 at yahoo dot com
14 years ago
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.
up
down
0nazgul26 (at_sign) windfox dot net
14 years ago
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 <= 5) decimalToFraction($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 > 0) simplifyFraction($fraction,$count,$top,$bottom);    else {        return "<font size=1>$bottom/$top</font>";    } } ?>
up
down
-1
php at keith tyler dot com
6 years ago
Another ordinal method, which does not involve utilizing date functions: <?php sprintf( "%d%s", $t, array_pop( array_slice( array_merge( array( "th","st","nd","rd"), array_fill( 4,6,"th")), $t%10, 1)));' ?>
up
down
-1
capripot at gmail dot com
5 years ago
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 - 9 : $v);    }    return ($add%10 == 0); } ?> Don't know if foreach and arrays operations are faster than while and substr, but I feel it clearer.
up
down
-1
bjcffnet at gmail dot com
12 years ago
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(5, 10, 15); echo average($array); // 10 ?>
up
down
-1
edward at edwardsun dot com
11 years ago
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.
up
down
-1
jerry dot wilborn at fast dot net
14 years ago
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));
up
down
-1
info at gavinvincent dot co dot uk
12 years ago
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; } } ?>
up
down
-1
AsherMaximum gmail
6 years ago
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 ? $1 : $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==1 ? $i.'st' : ( ($n2==2 ? $i.'nd' : ($n2==3 ? $i.'rd' : $i.'th') ) ) ) ?>
up
down
-1
Florian
11 years ago
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; } ?>
up
down
-1
jl85 at yahoo dot com
13 years ago
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)); }
up
down
-1
ian at mp3 dot com
16 years ago
for those looking for a credit card verification function i wrote a simple LUHN Formula algorithm: <?php $valid = 1; $numOfDigits = 0 - strlen($ccNumber); $i = -1; while ($i>=$numOfDigits){  if (($i % 2) == 0){    $double = 2*(substr($ccNumber, $i, 1));    $total += substr($double,0,1);    if (strlen($double > 1)){      $total += substr($double,1,1);    }  } else {    $total += substr($ccNumber, $i, 1);  }  $i--; } if (($total % 10) != 0){  $valid = 0; } ?>
up
down
-2
Mike
9 years ago
//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; }
up
down
-2
moikboy (nospam!) moikboy (nospam!) hu
11 years ago
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]; }; ?>
up
down
-2
help at gjbdesign dot com
12 years ago
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    } }?>
up
down
-2
marasek.SPAMLESS at telton.de
11 years ago
I could not resist to do a simpler version of the ordinal function: <?php function ordinal($num) {    $num = (int)$num;    $digit = substr($num, -1, 1);    $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.
up
down
-2
fabien_mornand at yahoo dot fr
13 years ago
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; ?>
up
down
-2
tembenite at gmail dot com
10 years ago
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)); }
up
down
-2
Chronial "at" cyberpunkuniverse.de
13 years ago
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; } ?>
up
down
-2
Aiden880
2 years ago
Lowest Common Denominator: function lcd($num, $start) {    while($num % $start != 0) {        $start++;    }    return $start; }
up
down
-3
eric at woolhiser dot com
12 years ago
For all you guys writing mortgage calculators out there: <?php function payment($apr,$n,$pv,$fv=0.0,$prec=2){    /* Calculates the monthly payment rouned to the nearest penny    ** $apr = the annual percentage rate of the loan.    ** $n   = number of monthly payments (360 for a 30year loan)    ** $pv    = present value or principal of the loan    ** $fv  = future value of the loan    ** $prec = the precision you wish rounded to    */    /****************************************\    ** No Warranty is expressed or implied. **    *****************************************/        if ($apr !=0) {        $alpha = 1/(1+$apr/12);        $retval =  round($pv * (1 - $alpha) / $alpha /        (1 - pow($alpha,$n)),$prec) ;    } else {        $retval = round($pv / $n, $prec);    }    return($retval); } ?>
up
down
-2
barry at megaspace dot com
10 years ago
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);
up
down
-2
daniel at g-loc dot org
11 years ago
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!
up
down
-2
monte at ohrt dot com
11 years ago
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 < 0 || $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++);
up
down
-2
jordanolsommer at imap dot cc
13 years ago
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 :).
up
down
-2
ddarjany at yahoo dot com
9 years ago
Tim's fix of Evan's ordinal function causes another problem, it no longer works for number above 100.  (E.g. it returns 111st instead of 111th).   Here is a further modified version which should work for all numbers. <?PHP function ordinal($cardinal)    {  $cardinal = (int)$cardinal;  $digit = substr($cardinal, -1, 1);  if ($cardinal <100) $tens = round($cardinal/10);  else $tens = substr($cardinal, -2, 1);  if($tens == 1)  {    return $cardinal.'th';  }  switch($digit) {    case 1:      return $cardinal.'st';    case 2:      return $cardinal.'nd';    case 3:      return $cardinal.'rd';    default:      return $cardinal.'th';  } } ?>
up
down
-4
lummox
9 years ago
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); }
up
down
-2
ausvald at tut dot by
13 years ago
I see there are some factorial functions below. I'll provide the best one: <? function factorial($n){ $n=(int)$n;  $f=1;  for(;$n>0;--$n) $f*=$n;  return $f; } ?>
up
down
-2
matthew_gaddis at yahoo dot com
14 years ago
Here is a cleaner factorial function: function factorial($s){    if($s) $r = $s * factorial($s - 1);    else $r = 1;    return $r; }
up
down
-2
jbeardsl at gte dot net
14 years ago
I needed a truncate function to operate on real numbers. I preferred not to use a string-manipulation method, so here's my solution. HTH... 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); }
up
down
-3
twoscoopsofpig at NOSPAM dot gmail dot com
11 years ago
@ Moikboy: This may or may not be more simplified factorialization: <?php $f=$fact=25; while ($fact>0) {$f=$f*$fact--;} echo $f; ?>
up
down
-3
graywh at gmail DELETE dot com
12 years ago
If you're really concerned about speed, you could compute the factorial of large numbers using the Gamma function of n-1. Integral y^(t-1)*Exp(-y) for y from 0 to Infinity For Fibonacci numbers, there's a better-than-recursive way. ((1+sqrt(5))/2)^(n/sqrt(5)) - ((1-sqrt(5))/2)^(n/sqrt(5))
up
down
-3
chris at free-source dot com
13 years ago
to "convert" scientific notation to a float simply cast it: <?php $val = '3.5e4'; $val = (float) $val; echo $val; ?> output: 35000
up
down
-3
patience at worldonline dot nl
15 years ago
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 < 2 )    $r = 1;  else {    for ( $i = $r-1; $i > 1; $i-- )      $r = $r * $i;  }  return( $r ); } ?>
up
down
-3
cornelius at skjoldhoej dot dk
16 years ago
I found that when dealing with tables, a 'least common multiple' function is sometimes useful for abusing tablespan and the likes. So here goes (you may choose to remove the first part of the gcd function if the function call is well-behaved): <?php function gcd(n, m) //greatest common divisor {    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) //least common multiple {    return m*(n/gcd(n,m)); } ?> This may or may not be something to consider adding to the mathematical function library.
up
down
-3
erikvandeven100 at gmail dot com
9 months ago
This is my factorial method <?php function factorial($nr) {    $product = array_product(range(1,++$nr));    return $product / $nr; } ?> It uses the reversed method by applying division instead of multiplication, so it even returns the right answer when entering 0.
up
down
-3
tim at durge dot org
10 years ago
In Evan's ordinal function, the line: <?php  $tens = substr($cardinal, -2, 1); ?> needs to be replaced by: <?php  $tens = round($cardinal/10); ?> or similar. At least on PHP 4.3.10,  substr("1", -2, 1)  returns '1' - so Evan's function gives "1th", as well as "11th".  This is contrary to the documentation, but is noted in the comments on the substr manual page.
up
down
-4
donnieb819 at hotmail dot NOSPAM dot com
12 years ago
Method to convert an arbitrary decimal number to its most reduced fraction form (so a string is returned, this method would probably be used for output formatting purposes.)  There were other methods similar to this one on the page, but none did quite what I wanted.  It's maybe not the most elegant code, but it gets the job done.  Hope this helps someone.  An iterative form of Euclid's algorithm is used to find the GCD. <?php function dec2frac( $decimal ) {  $decimal = (string)$decimal;  $num = '';  $den = 1;  $dec = false;    // find least reduced fractional form of number  for( $i = 0, $ix = strlen( $decimal ); $i < $ix; $i++ )  {    // build the denominator as we 'shift' the decimal to the right    if( $dec ) $den *= 10;        // find the decimal place/ build the numberator    if( $decimal{$i} == '.' ) $dec = true;    else $num .= $decimal{$i};  }  $num = (int)$num;      // whole number, just return it  if( $den == 1 ) return $num;      $num2 = $num;  $den2 = $den;  $rem  = 1;  // Euclid's Algorithm (to find the gcd)  while( $num2 % $den2 ) {    $rem = $num2 % $den2;    $num2 = $den2;    $den2 = $rem;  }  if( $den2 != $den ) $rem = $den2;      // now $rem holds the gcd of the numerator and denominator of our fraction  return ($num / $rem ) . "/" . ($den / $rem); } ?> Examples: echo dec2frac( 10 ); echo dec2frac( .5 ); echo dec2frac( 5.25 ); echo dec2frac( .333333333 ); yields: 10 1/2 21/4 333333333/1000000000
up
down
-4
rubo77 at spacetrace dot org
9 years ago
<?php function lcd($n,$m, $maxvarianzpercent=0){    // set $maxvarianzpercent=5 to get a small, but approx. result    /* a better lcd function with varianz:    for example use    lcd(141,180,5) to get the approx. lcd '7/9' which is in fact 140/180    */    // ATTENTION!!! can be really slow if $m is >1000        $d=$n/$m;    $f=1;    while($d*$f!=intval($d*$f)){        $f++;    }    $r=($d*$f).'/'.$f;    if(($d*$f)<=10 or $f<=10) return $r;    else if($maxvarianzpercent>0){        $f=1;        while($d*$f!=intval($d*$f) and ($d*$f)-intval($d*$f) > $maxvarianzpercent/100){            $f++;        }        return intval($d*$f).'/'.$f;    } else return $r; } ?>
up
down
-4
Evan Broder
11 years ago
A slightly more complex but much more accurate cardinal=>ordinal function (the one below doesn't account for 11th, 12th, and 13th, which don't follow the usual rules): <?php    function ordinal($cardinal)    {        $cardinal = (int)$cardinal;        $digit = substr($cardinal, -1, 1);        $tens = substr($cardinal, -2, 1);        if($tens == 1)        {            return $cardinal.'th';        }                switch($digit)        {        case 1:            return $cardinal.'st';        case 2:            return $cardinal.'nd';        case 3:            return $cardinal.'rd';        default:            return $cardinal.'th';        }    } ?>
up
down
-4
shanx at shanx dot com
15 years ago
<? /** * Function to calculate base36 values from a number. Very * useful if you wish to generate IDs from numbers. * * @param $value The number * @param $base The base to be applied (16, 36 or 64) * @return The calculated string * @author Shashank Tripathi ([email protected]) * @version 0.1 - Let me know if something doesnt work * */ function base36($value, $base) {    $baseChars = array('0', '1', '2', '3', '4', '5',                       '6', '7', '8', '9', 'a', 'b',                       'c', 'd', 'e', 'f', 'g', 'h',                       'i', 'j', 'k', 'l', 'm', 'n',                       'o', 'p', 'q', 'r', 's', 't',                       'u', 'v', 'w', 'x', 'y', 'z'                     );    $remainder = 0;    $newval = "";        while ( $value > 0 )    {        $remainder = $value % $base;        $value = ( ($value - $remainder)/ $base );        $newval .= $baseChars[$remainder];    }    return strrev($newval);     } echo "The string for 46655, for instance, is " . base36(46655, 36); ?>
up
down
-5
jos at gtacrime dot nl
11 years ago
Thanks to Chronial "at" cyberpunkuniverse.de, I was able to create the binompdf(n, p, k) function. <?php function nCr($n, $k){   if ($k > $n)     return NaN;   if (($n - $k) < $k)     return nCr($n, ($n - $k));   $return = 1;   for ($i=0; $i<$k; $i++){     $return *= ($n - $i) / ($i + 1);   }   return $return; } function binompdf($n, $p, $k){    $return = nCr($n, $k) * pow($p, $k) * pow((1 - $p), ($n - $k));    return $return; } ?>
up
down
-5
webkid%webkid.com
15 years ago
I found it kind of irritating that PHP had no n
0 notes
vfontjr · 8 years ago
Text
New Post has been published on Victor Font Consulting Group, LLC
New Post has been published on https://victorfont.com/customize-formidable-forms-email-mime-type/
Customize Formidable Forms Email Mime Type
On the Formidable Forms Community Support Forum, a customer asks,
How do I change the mime type of an email to text/x-gm-impdata so the content can be imported into Goldmine?
Formidable uses the WordPress wp_mail() function to send emails. Unless otherwise specified, the wp_mail function defaults the content type (mime) of any email to text/plain. The function provides a filter that allows you change the content type. The filter is wp_mail_content_type. To change the mime type for all emails, you would use:
add_filter( 'wp_mail_content_type', 'set_content_type' ); function set_content_type( $content_type ) return 'text/x-gm-impdata';
Unfortunately, I've tested this and it doesn't work with Formidable. Instead of using the WordPress supplied filter, Formidable hard codes the mime type as 'text/plain' or 'text/html'. Formidable also has an undocumented filter called frm_email_header that we can use to manipulate the content or mime type. If we examine the output of this filter, just prior to Formidable's call to wp_mail, the header contains a three element array that has the following content (as viewed with the Kint debugger):
The value of the third element will either be Content-Type: text/html; charset="UTF-8" or Content-Type: text/plain; charset="UTF-8". Knowing this, we can change the mime type prior to the send action. Since this is a simple array, the way to do this is to remove the third element and replace it with the new content type. The code looks like this:
add_filter('frm_email_header', 'change_email_content_type'); function change_email_content_type($header) /* remove the Content Type element of the array (the last element) */ array_pop($header); /* needed to preserve compatibility */ $charset = get_option('blog_charset'); $content_type = 'Content-Type: text/x-gm-impdata; charset="' . esc_attr( $charset ) . '"'; $header[] = $content_type; return $header;
This works perfectly, but it changes the mime type for all emails sent by Formidable. So this needs to be wrapped in code that limits it to the specific form. This also may not work at all if you are using a 3rd party SMTP server such as Mandrill or Sparkpost. When I was testing this code in my local environment, I had Sparkpost enabled and Sparkpost kept changing the content type back to text/html. My recommendation is not to use any 3rd party SMTP sender with this process.
The last step is to wrap the apply frm_email_header filter in a formidable hook that fires after submit but before the email is sent. For this we can use the frm_pre_create_entry hook.
add_filter('frm_pre_create_entry', 'adjust_my_email_header'); function adjust_my_email_header($values) if ( $values['form_key'] == 'contact2' ) add_filter('frm_email_header', 'change_email_content_type'); return $values; function change_email_content_type($header) /* remove the Content Type element of the array */ array_pop($header); /* needed to preserve compatibility */ $charset = get_option('blog_charset'); $content_type = 'Content-Type: text/x-gm-impdata; charset="' . esc_attr( $charset ) . '"'; $header[] = $content_type; return $header;
Note that I use form_key instead of form_id. When you migrate a Formidable form to a different environment using export/import, the form id will change. The form key remains static. Using form key will save you a headache tracking down why your code doesn't work after moving to a different environment. Just remember to change the form_key in your code from 'contact2' to the key of your form.
If this all works for you, viewing the email source code will display a header similar to this one:
0 notes