Browse | Submit A New Snippet
Snippets by category: Algorithms
| Snippet ID | Title | Creator |
| Snippets | ||
| 10 | Quick Sort Function | doggy8088 |
| a quick sort function Very useful! | ||
| 11 | In String | jeremycreed |
| 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. | ||
| 12 | bubblesort | jeremycreed |
| 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. | ||
| 19 | ROT13 Encoding Function | brettb |
| 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. | ||
| 27 | Binary Search Algorithm | ravi_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. | ||
| 38 | Paswoord generator | baranyai |
| Very simple script which generates an 8 digit paswoord cinsisting of letters and numbers and capital letters | ||
| 39 | PHP Weather | gimpster |
| 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. | ||
| 41 | Generate a 8 chr random string, only using undercase letters | r-f-b |
| very short function, 6 lines long. | ||
| 43 | HTML Mime Email | heyesr |
| 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 | ||
| 61 | Haversine 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. | ||
| 63 | HTML parser | smooc |
| 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) | ||
| 82 | Create Multidimensional Array | jsmirnio99 |
| A function that takes as input a character-delimited string and returns a multidimensional array. | ||
| 86 | Calculate Directory Size | bonnej |
| Recursively determines the size of a directory. | ||
| 107 | Email Validator | neilm |
| Will check to see if an email address is in the proper format. | ||
| 157 | Password Generator | coolmax |
| This function return Password consists of 0-9, a-z, A-Z | ||
| 166 | strip | smarlowe |
| 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 string | wojas |
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. | ||
| 176 | Multiple page includes with random order | richierich |
| 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" | ||
| 179 | Pronounceable Password Generator | sebastien |
| Create a random pronounceable password, with random case. Can be easily customized. | ||
| 188 | Simple Encryption based on Multidimensional ARRAy | psaurabh |
| 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 | ||
| 1305 | Generate 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'); | ||
| 211 | Customizable Random Password Generator | digit4l |
| 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. | ||
| 1062 | WHOS ONLINE? | ridwank |
| This script is for tracking online user by IP/Host. its very simple, no cookies or session need. | ||
| 251 | 'Bad word' Function | knickerlas |
| A little function that checks a string for 'bad words'. | ||
| 269 | array_key() | lemming |
| function that returns the numeric key of the array given the value, usefull when 'walking' thru arrays in multiple files... | ||
| 338 | Email Validity | sanjeev_vaidya |
| Check if the entered email address is valid or not. | ||
| 337 | Quoted Printable encoding | gpietrella |
| This function converts a string to a quoted printable string. It uses PERL regular expression to do it. | ||
| 453 | Morse Coder | mavetju |
| Morse-code encoder/decoder | ||
| 469 | punch card convertor | mavetju |
| Convert strings into punch cards | ||
| 470 | Papertape convertor | mavetju |
| Convert strings into papertape | ||
| 471 | monotone list checking functions | matto |
| 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. | ||
| 474 | Boolean Keyword Search | tflinton |
| This will format a boolean keyword search into an array that you can use to search any source. | ||
| 493 | Decode CueCat data | ulbador |
| These functions will decode the so called encryption algorithm that the cuecat scans in, resulting in usable data. | ||
| 529 | Generate a range of numbers | mp96brbj |
| 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. | ||
| 542 | Numbers and Commas | phaseiii |
| 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". | ||
| 1297 | Sudoku | kcyster |
| 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 | ||
| 700 | Verilog / VHDL - little vs big Endian | robintsang |
| 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. | ||
| 588 | Is Email | agentkelly |
| Email format validator :) | ||
| 594 | Convert Between Numeric Bases | cheald |
| 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. | ||
| 606 | advanced 2D array sort | jpristel |
| sorts arrays of the form: $array_name[$some_integer][$some_key] by the 2nd key ("$some_key") for example: $userdata[1]["username"] | ||
| 624 | two-dimensional factorial (sorta) function | tom_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! | ||
| 668 | The Slasher | ldavis |
| 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. | ||
| 1184 | Calculate Distance Between Two ZIP Codes or Postal Codes | tgotchi |
| 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. | ||
| 1261 | Secure password generator | montaro |
| 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. | ||
| 714 | Dijkstra´s Algorithm Shortes Path | santi900 |
| 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. | ||
| 730 | MakeSql | eofoloco |
| As The Name Says :-) | ||
| 729 | Php Dot it | eofoloco |
| 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! | ||
| 740 | Order 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. | ||
| 744 | Ford-Fulkerson Transport Problem Algorithm | zwols |
| This is a PHP implementation of the Ford-Fulkerson algorithm for solving the standard linear programming transport problem. | ||
| 745 | Prime tester | foxtrot |
| 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. | ||
| 746 | QUICK random string generator | warmwind |
| function that returns password of length n containing alphanumeric characters (A-z, a-z, 0-9) | ||
| 1317 | Get differences in Arrays | bpat1434 |
| 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. | ||
| 803 | Postal 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. | ||
| 1392 | Nitobi ComboBox V3 | nitobi |
| 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. | ||
| 817 | international Emailchecker | berni |
| This functions checks if is an Email an valid international Emailaddress. More Information at http://www.php-resource.de | ||
| 826 | recursive array dump | examancer |
| 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). | ||
| 873 | Search Criteria Parser | aholimal |
| 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>. | ||
| 892 | Vechicle VIN number check digit calculator | bigfriz |
| 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! | ||
| 896 | Time 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 | ||
| 900 | Navigation Tree | aholimal |
| 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. | ||
| 925 | test3 | farooqsam |
| tertertert | ||
| 945 | Month 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. | ||
| 1260 | Valiates | kthakore |
| Show how to validate various things. name, email, phone number, time, numerical data. | ||
| 1290 | A light form of encryption and decryption-without libmcrypt | toplay |
| 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. | ||
| 1028 | Parsing String and Count with show individual data | himadrish |
| 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. | ||
| 1037 | Capitalize first word of every sentence | jpetrovich |
| 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! | ||
| 1275 | Swap Values without using third variable | vin_quest |
| Simple script for swaping 2 variables without using third variable. | ||
| 1064 | ShellSort Function | maldar |
| This is one of best sorting algorithm that use for sorting quickly . it's order is sqr(n) | ||
| 1068 | Merge Sort Function | maldar |
| 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 | ||
| 1072 | Convert Number To Letter -Spanish- | lechuza |
| This code translate a number to letter in Spanish | ||
| 1103 | phonetest | mattlarson29 |
| takes user input, parses out any non-numeric characters, and returns the phone number in the form (###) ###-#### x#### (if more than 10 digits). | ||
| 1151 | Simple Tree | klingo |
| 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. | ||
| 1342 | Passing the screen resolution to a querystring | fraseathome |
| 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. | ||
| 1412 | RGB to HEX - HEX to RGB Convert Function | halityesil |
| 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 | ||
| 1430 | Priority based object Mixer class | ortega |
| 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. | ||
| 1439 | Prime factorization | lillefix |
| Factorizes a given number. | ||
| 1447 | Weighted Random Number Generator | seismos |
| 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. :) | ||
| 1466 | PHP stealthing - .htaccess generator | boss420 |
| 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 | ||
| 1471 | The Smartest way to generate random passwords | karray |
| Generate random password from a set of chars ($pool) | ||
| 1474 | Create Random Password | eyeswideshut25 |
| Very simple small code to generate random password. | ||

