Browse | Submit A New Snippet

Snippets by category: Algorithms

Snippet ID Title Creator
Snippets
10Quick Sort Functiondoggy8088
a quick sort function
Very useful!
11In Stringjeremycreed
This function returns the position of string s1 within string s2. The position is 1 based. If s1 is not in s2, 0 is
returned.
12bubblesortjeremycreed
This is a simple bubblesort by Petter Nilsenthat takes 2 arrays as argument.The first one is the actual data used for sorting, the second is data that will "tag along" with the first array, for instance a descriptive text about the data in the first array.
19ROT13 Encoding Functionbrettb
ROT13 is a useful method of encoding text so that it cannot easily be read. The method originated on USENET, where it was commonly used to hide answers to jokes and spoilers for forthcoming TV show episodes.
27Binary Search Algorithmravi_php
Binary search algorithm function. Takes an array as an argument and the element to be searched for in the array. Returns '1' if found, '0' if not. The code can be modified slightly to return the array index of the found element.
38Paswoord generatorbaranyai
Very simple script which generates an 8 digit paswoord cinsisting of letters and numbers and capital letters
39PHP Weathergimpster
PHP Weather makes it easy to show the current weather on your webpage.
It works by fetching the most recent weather-report (METAR) from an airport of your choice. It then decodes the report, and gives you an easy access to the individual parts: temperature, wind speed and direction etc.
See http://www.gimpster.com for instructions on how to use PHP Weather.
41Generate a 8 chr random string, only using undercase lettersr-f-b
very short function, 6 lines long.
43HTML Mime Emailheyesr
A class for sending mime based email. It can send:

HTML Email
HTML Email with embedded images
HTML Email with attachments
HTML Email with embedded images and attachments
Text email
Text email with attachments
61Haversine Formula (dist between two lat/long pairs)airdish
Determines the distance in miles between two latitude/longitude pairs (in degrees) with a slightly modified Haversine formula (from R.W. Sinnott, "Virtues of the Haversine",
Sky and Telescope, vol. 68, no. 2, 1984, p. 159). See http://earth.uni-muenster.de/~eicksch/GMT-Help/msg00147.html for more info. It was modified for speed.
63HTML parsersmooc
Actually this code parses every formatted text tagged with < & >. Look at the code for some explanation. It heavily updated at the moment (I need it as an OFX parser, more on that later), so it might be worth to check it out. Probably arguments wont work, because I have not yet tested it (I do not need it when pasring OFX)
82Create Multidimensional Arrayjsmirnio99
A function that takes as input a character-delimited string and returns a multidimensional array.
86Calculate Directory Sizebonnej
Recursively determines the size of a directory.
107Email Validatorneilm
Will check to see if an email address is in the proper format.
157Password Generatorcoolmax
This function return Password consists of 0-9, a-z, A-Z
166stripsmarlowe
A program to process large dataset files one record at a time and throw away certain records while retaining others.

It is very fast and uses very little memory, and has been tested on files of several hundred megabytes. We use it for filtering and processing log files here to throw away uninteresting entries for usage reporting.
175 converting a PHP array into a stringwojas

This simple function converts a PHP array to a string containing a PHP array declaration. It can be used to put an array into a database field. It can then be retrieved and eval()'d in another script.
176Multiple page includes with random orderrichierich
This script includes 7 files in a random order. The files are named thisfile1.php3 through to thisfile7.php3.

To change the number of files modify $i<=7.
To change the initial part of the name or the extension change "thisfile".$value.".php3"
179Pronounceable Password Generatorsebastien
Create a random pronounceable password, with random case.
Can be easily customized.
188Simple Encryption based on Multidimensional ARRAypsaurabh
This is a code which will encrypt any text. you can make your own encryption call. You have to add encryption value in the multidimensional array at the begning of the code
1305Generate a random string.shugotenshi
Generate a random string based on a supplied length and seed.

// Generates a 4 character random string,
// using the seed 'abcd'
$randomStr = getRandomStr(4, 'abcd');
211Customizable Random Password Generatordigit4l
Random password generator that you can customize to include uppcase letters, lowercase letters, and numbers, as well as the length of the password. Read the comments for more info.
1062WHOS ONLINE?ridwank
This script is for tracking online user by IP/Host. its very simple, no cookies or session need.
251'Bad word' Functionknickerlas
A little function that checks a string for 'bad words'.
269array_key()lemming
function that returns the numeric key of the array given the value, usefull when 'walking' thru arrays in multiple files...
338Email Validitysanjeev_vaidya
Check if the entered email address is valid or not.
337Quoted Printable encodinggpietrella
This function converts a string to a quoted printable string. It uses PERL regular expression to do it.
453Morse Codermavetju
Morse-code encoder/decoder
469punch card convertormavetju
Convert strings into punch cards
470Papertape convertormavetju
Convert strings into papertape
471monotone list checking functionsmatto
if a user has to order items (e.g. in a questionnaire), check if they are correctly ordered.
you can check for monotone and strictly monotone lists.
474Boolean Keyword Searchtflinton
This will format a boolean keyword search into an array that you can use to search any source.
493Decode CueCat dataulbador
These functions will decode the so called encryption algorithm that the cuecat scans in, resulting in usable data.
529Generate a range of numbersmp96brbj
Syntax:
array steps(double start, double end, int steps)

Returns an array of numbers, beginning with $start and gradually incrementing it so that the final number is $end.
You decide how many numbers you want in the list, and the function will modify the incrementation accordingly.
It will return a minimum of 2 munbers ($start and $end), no matter how small $steps is.
542Numbers and Commasphaseiii
Syntax:

numcomma("$value");

This function takes a numeric value, and adds commas where applicable. If you gave it the value of "2930829523", then it would return "2,930,829,523".
1297Sudokukcyster
So, the sudoku craze has swept the world. "Everyone" has built soduko solvers, but where are the sudoku generators. This function does just that! It allows you to generate a random "solved" sudoku with the associated puzzle
700Verilog / VHDL - little vs big Endianrobintsang
A script for you to easily to change all big-endian wires to big-endian in a Verilog file. this script was written for an x86 machine where there are only 8, 16, 32 bit registers. if you have a machine for 64 bits, modiy the code to what you need.

the variable i used in the script is called ir_in[127:96]
the file this script reads must be called file.v

have fun. it'll save you some time.


588Is Emailagentkelly
Email format validator :)
594Convert Between Numeric Basescheald
Use to convert a number in any base from 2 to 36 to any other base from 2 to 36. ie: convertBase("FF",16,10) returns 255. You can also use HEX, BINARY, BASE10, DECIMAL and OCT in place of numeric values for the bases. ie: convertBase("FF",HEX,BINARY) returns 11111111.
606advanced 2D array sortjpristel
sorts arrays of the form:
$array_name[$some_integer][$some_key]
by the 2nd key ("$some_key")
for example:
$userdata[1]["username"]
624two-dimensional factorial (sorta) functiontom_arrow
given a 2d array, function will return a 1d array containing strings for all possible column combinations of 2d array. tiny bug that results in an incomplete sentence being returned when iterating down left most column, but all in all, works great! took a while to figure out!
668The Slasherldavis
This function removes ALL backslashes from any given variable. It should work with PHP3 and PHP4. It can be used in place of the native stripslashes() function.
1184Calculate Distance Between Two ZIP Codes or Postal Codestgotchi
This algorithm calculates distance between two coordinates ie. latitude and longitude from ZIP code or postal code. It is suitable for store locator, route planner, shipment estimation etc.
1261Secure password generatormontaro
This is a secure password generator. It uses random seeds to assure best randomization. It comes in the form of three strengths:

1) Uberstrong (A-Z, a-z, 0-9, special chars (ie. !@#$%&*(), etc), 26 chars in length.
2) Strong (A-Z, a-z, 0-9), 26 chars in length.
3) Strong-but-compatible (A-Z, a-z, 0-9), 12 chars in length.

I have tested them all on securitystats.com and they have given good results (Uberstrong gives full security, Strong and Strong-but-compatible gives about 80% security).

All code reasonably commented, so you should be able to get around it alright.
714Dijkstra´s Algorithm Shortes Pathsanti900
This function allows to trace the shortest path beetwen nodes and traces the route, for example on a map. I found on a forum and i think it´s very good, altougth i think it doesn´t works properly on >PHP 4.0.
730MakeSqleofoloco
As The Name Says :-)
729Php Dot iteofoloco
A Simple routine to cut a string .
If the string has a number of characters higher than
desired, the function returns the number of characters desired and 3 dots(or more, as you modify the function).
If the string has a number of characters lower than the max. desired the function returns the full string...!

Example:

echo lefts( "Oh My God!", 5 );
returns :
Oh My ...

echo lefts( "Oh My God!", 20 );
returns :
Oh My God!
740Order by clause sort routine for multi-dimension array!jasonpell
This function allows you to sort and array of the form:
array(
array(title=>'Crow, The', owner_id=>'jpell', s_item_type=>'DVD'),
array(title=>'Rambo', owner_id=>'martin', s_item_type=>'DVD'),
array(title=>'Good Will Hunting', owner_id=>'lucy', s_item_type=>'VHS')
);

By specifying a order_by_clause of the form:

'title ASC, owner_id ASC, s_item_type DESC'.

The get_usort_function() will return a generated function for use with create_function:

$title=strcmp($a[title], $b[title]); if($title==0){$owner_id=strcmp($a[owner_id], $b[owner_id]); if($owner_id==0){return strcmp($b[s_item_type], $a[s_item_type]);}else{return $owner_id;}}else{return $title;}

You then call usort thus:

usort($item_rs, create_function('$a,$b', get_multisort_function('title ASC, owner_id ASC, s_item_type DESC')));

Ensure you use '$a,$b' as the first argument to create_function, as the generated function relies on the names and the order.
744Ford-Fulkerson Transport Problem Algorithmzwols
This is a PHP implementation of the Ford-Fulkerson algorithm for solving the standard linear programming transport problem.
745Prime testerfoxtrot
Two methods:
is_prime - Test if a number is prime.
get_prime - Find a prime within a given range.

Uses the Miller-Rabin randomized primality test.
746QUICK random string generatorwarmwind
function that returns password of length n containing alphanumeric characters (A-z, a-z, 0-9)
1317Get differences in Arraysbpat1434
This function will allow you to get all the differences in multiple arrays (up to 3 arrays).
Inspired by Phence (on the forums), this will return an array filled with all the differences between all the arrays, not just the first.
803Postal Code Validator!rudyrockstar
Validates postal code based on country (currently just us/ca/uk).

postalcodevalidate($ctry,$postcode)

Assumes the use of the international 2 letter country code e.g "us" for USA, "ca" for canada.
1392Nitobi ComboBox V3nitobi
An AJAX based JavaScript autocompletion control with extensive cross browser and cross platform compatibility. V3 offers six unique search behaviours including 'fuzzy' substring searching, and a robust cross-browser DHTML rendering engine.
817international Emailcheckerberni
This functions checks if is an Email an valid international Emailaddress.

More Information at http://www.php-resource.de
826recursive array dumpexamancer
have you ever wanted to quickly see the contents of an array? This function dumps an array into a string recursively using key:value pairs. All values are tested to see if they are an array, and if so, are split into key:value pairs recursively until everything is a string. The key:value seperators, and key:key seperators are configurable through the function call (you don't have to change any variables).
873Search Criteria Parseraholimal
Code to interpret a search criteria which contains boolean operators (and, not , or) and opening and closing brackets ( and ) into tokens and parse it for correctness. You can then read the tokens like in a switch statement and add code such as mysql's LOCATE(<token>,<text column in a mysql table>)>0 to each non reserved (ie not "and", "or", "not",
")" , "(" ) token (a keyword) to check that it appears in the <text column in a mysql table>.
892Vechicle VIN number check digit calculatorbigfriz
Put in a 17 digit VIN number and it tells you if the check digit computes or not.
Future plans include extracting the manufacturer and other known information from the VIN. If anyone writes a class from this code please share here. phpbuilder rocks!
896Time date kakchan
This script usefull when you have a server outside your country and you want to see the right time..if you want to contact my my web community is on http://www.dawnofdreams.org
900Navigation Treeaholimal
Navigation Tree which uses Mysql to store as many trees as you like. Has two main files, treeclass.inc and tree.php. Can have as many levels in the tree as physical limitations can handle. Uses a recursive function to prepare the tree to display.
925test3farooqsam
tertertert
945Month Mine leonardburton
This function Comes from The Function Junction at www.discountsexpress.com/PHPFJ and was created by Leonard Burton lbburt0@pop.uky.edu. Unrestricted Release.

This function was created to mine dates from two distinct expense and income tables for a ledger application. It expexts a Ymd format in the date fields and returns a sorted array with the format of Ym.
1260Valiateskthakore
Show how to validate various things. name, email, phone number, time, numerical data.
1290A light form of encryption and decryption-without libmcrypttoplay
You will be able to do a light sort of encryption and decryption using these encode() and decode() functions (without the use of mcrypt/libmcrypt). Functions require PHP ver >= 4.2.0.

After using encode(), remember to save the IV along with the encrypted value, so you'll be able to decrypt it later. The encrypted value and IV can be saved in a flat file, database, or passed along in the URL (and in hidden form fields too).

This code is presented under the GPL and comes with no support and no warranties whatsoever. Use at your own risk.

Enjoy.
1028Parsing String and Count with show individual datahimadrish
This function created for parsing a set of word from a sentence Mainly used for searching where many search criteria concatenate by special character like '+', ',' etc..
This module parse the whole sentence and the individual. It also count how many search criteria do user input. Created on 30th December,2002 by Himadrish Laha himadrish@yahoo.com />
You can also used it under GNU Lisence Rule, but must used author content in your script.
1037Capitalize first word of every sentencejpetrovich
This dandy function uc_sentences that I made will capitalize the first word of every sentence. It's very nice as opposed to uc_words which looks tacky and is hard to read. Hopefully the PHP gods will put this into the next build they conjure up. My email is jdpetrov@mtu.edu if you have any questions or comments. Thanks!
1275Swap Values without using third variablevin_quest
Simple script for swaping 2 variables without using third variable.
1064ShellSort Functionmaldar
This is one of best sorting algorithm that use for sorting quickly . it's order is
sqr(n)
1068Merge Sort Functionmaldar
This function gets two sorted array and their's length ,then combine this two array in one and holds their sorted state.
Currently this function mergging only two sorted (numeric,string) array and can develope to merge more . I welcome any sugesstion or comment about it.my E-mail address is : masuod_maldar@yahoo.com
1072Convert Number To Letter -Spanish-lechuza
This code translate a number to letter in Spanish
1103phonetestmattlarson29
takes user input, parses out any non-numeric characters, and returns the phone number in the form (###) ###-#### x#### (if more than 10 digits).
1151Simple Treeklingo
This is a simple implementation of a Tree structure using matrix Queue representation. Functions for adding elements and listing the tree. I used it for a directory tree implementation.
1342Passing the screen resolution to a querystringfraseathome
This code snippet will pass the users screen resolution on to a querystring. This avoids cookies and other snippets which don't seem to work out there.
1412RGB to HEX - HEX to RGB Convert Functionhalityesil
RGB to Hex
Hex to RGB
Function

echo '#FFFFFF => '.rgb2hex2rgb('#FFFFFF').'<br>';
echo '#FFCCEE => '.rgb2hex2rgb('#FFCCEE').'<br>';
echo 'CC22FF => '.rgb2hex2rgb('CC22FF').'<br>';
echo '0 65 255 => '.rgb2hex2rgb('0 65 255').'<br>';
echo '255.150.3 => '.rgb2hex2rgb('255.150.3').'<br>';
echo '100,100,250 => '.rgb2hex2rgb('100,100,250').'<br>';


#FFFFFF =>
Array{
red=>255,
green=>255,
blue=>255,
r=>255,
g=>255,
b=>255,
0=>255,
1=>255,
2=>255
}


#FFCCEE =>
Array{
red=>255,
green=>204,
blue=>238,
r=>255,
g=>204,
b=>238,
0=>255,
1=>204,
2=>238
}
CC22FF =>
Array{
red=>204,
green=>34,
blue=>255,
r=>204,
g=>34,
b=>255,
0=>204,
1=>34,
2=>255
}

0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA

1430Priority based object Mixer classortega
I was using symfony's sfMixer class. Thought why not create one's own

This class mixes different object and u can call methods on the component objects (see demo class). Priority can be also assigned to the objects. All the objects in the Mixer are singletons.
1439Prime factorizationlillefix
Factorizes a given number.
1447Weighted Random Number Generatorseismos
This is a function that randomly generates an integer between two specified integers (which may include them). It works just like rand() except it has a factor parameter which specifies how exponential the probability differences between numbers can be. Passing a value of 1, in this case would give all numbers in the range an equal chance of being selected. A value of 2 should be sufficient in most cases, but it you want high numbers to occur less frequently, use higher values.

This function can be used for getting random indexes from an array, where the lower the index, the higher the chances of it being selected. It can also be used for randomly pulling lines from a flatfile, where the first line is most likely to be chosen, and where the last line is least likely to be chosen.

This function wasn't tested with negative or floating-point values, so be warned.

You may use this freely or modify it at your own will. I'm just glad to share the solution to a problem I spent all day on. :)
1466PHP stealthing - .htaccess generatorboss420
Use this simple tool to stealth PHP extensions. You can use any extension, to make it look like other languages (.asp , .cfm, .pl , etc)

Or anything just for fun, such as .abc

1471The Smartest way to generate random passwordskarray
Generate random password from a set of chars ($pool)
1474Create Random Passwordeyeswideshut25
Very simple small code to generate random password.