Accessing a Variable Outside a Function

When inside a function, you cannot, by default, access any variables from outside that
function.This behavior can be changed, however, for specific variables by using the
global language construct on it inside the function.

<?php
$name = 'Ramsey';
function print_and_change_name() {
// Declare the variable $name to be accessible within this function
global $name;
// Output this name, and then change the name.
echo "<p>{$name}</p>";
$name = 'Heather';
}
// Call the function once and it prints: 'Ramsey'
print_and_change_name();
// Call the function again, and it prints: 'Heather'
print_and_change_name();
?>

Continue reading

Popularity: 7% [?]

Variables Quick Hits

 

Check whether a variable has been given a value:

$bool = isset($variable);

This function returns true if the variable exists and is not NULL.

Check whether a variable is empty:

$bool = empty($variable);

This function defines the broad concept of an “empty” variable: a variable that may be set but has
a null or zero value. Specifically, this function returns true if the variable has any of the following
values or properties: “”, 0, “0″, NULL, false, or array().
Full documentation: http://php.net/empty Continue reading

Popularity: 8% [?]

Simulating Dice

Softstuff4u Lucky dice

DICE

Random number generation is a useful tool that programmers find themselves using
regularly. One potential use is to simulate the rolling of dice.

<?php
// Dice Simulator
 function roll_dice($number, $sides, $values = false) {
 // Loop as much as needed filling an array with the random die rolls.
 $dice = array();
 for ($i = 0; $i < $number; $i++) {
 $dice[] = rand(1, $sides);
 }
 // If the optional 3rd parameter is set to true, return the dice array:
 if ($values) {
return $dice;
 } else {
 // Otherwise, return the sum of the dice:
 return array_sum($dice);
 }
 }
 // Roll 3 six sided dice and echo their result (between 3 & 18)
 $roll_3d6 = roll_dice(3, 6);
 echo "<pre>Dice roll = {$roll_3d6}\n";
 // Roll a 100 sided die, 10 times, and echo all the values:
 $rm_stats = roll_dice(10, 100, true);
 print_r($rm_stats);
 echo '</pre>';
 ?>

This function has two purposes. If you call it just passing it two parameters—the number
of times to roll the die and how many sides it has—it will roll them all, add up a total,
and just return that total. However, if you provide an optional third parameter of “true”,
instead after rolling the dice it returns an array full of values.
A more versatile function is created this way; however, at a slight performance hit if
all you ever want to do is get the sum of the dice. In that case, the creation of the array
is not needed because the sum could just be added as the loop progresses.

Popularity: 73% [?]

Queue Implementation using PHP

The opposite of a stack, a queue is a data structure that follows a FIFO (First In First
Out) rule.This means that it works like a line at a movie theater.The person who gets in
line first, gets served first.

<?php
// A library to implement stacks in PHP via arrays
 // The Initialize function creates a new stack:
 function &stack_initialize() {
 // In this case, just return a new array
 $new = array();
 return $new;
}
 // The destory function will get rid of a stack
 function stack_destroy(&$stack) {
 // Since PHP is nice to us, we can just use unset
 unset($stack);
 }
 // The push operation on a stack adds a new value onto the top of the stack
 function stack_push(&$stack, $value) {
 // We are just adding a value to the end of the array, so we can use the
 // [] PHP Shortcut for this. It's faster than using array_push
$stack[] = $value;
 }
 // Pop removes the top value from the stack and returns it to you
 function stack_pop(&$stack) {
 // Just use array pop:
 return array_pop($stack);
 }
 // Peek returns a copy of the top value from the stack, leaving it in place
 function stack_peek(&$stack) {
 // Return a copy of the value on top of the stack (the end of the array)
 return $stack[count($stack)-1];
 }
 // Size returns the number of elements in the stack
 function stack_size(&$stack) {
 // Just using count will
give the proper number:
 return count($stack);
 }
 // Swap takes the top two values of the stack and switches them
 function stack_swap(&$stack) {
 // Calculate the count:
 $n = count($stack);
 // Only do anything if count is greater than 1
 if ($n > 1) {
 // Now save a copy of the second to last value
 $second = $stack[$n-2];
 // Place the last value in second to last place:
 $stack[$n-2] = $stack[$n-1];
 // And put the second to last, now in the last place:
 $stack[$n-1] = $second;
 }
 }
?>

 

Popularity: 15% [?]

Posted in Daily Notes, PHP | Leave a reply

Spell-Checking Words in a String

You want to check if one or more words are spelled correctly.

Use PHP’s ext/pspell extension to check words against an internal dictionary:

<?php
// define string to be spell-checked
 $str = "someun pleez helpp me i canot spel";
 // check spelling
 // open dictionary link
 $dict = pspell_new("en", "british");
 // decompose string into individual words
 // check spelling of each word
 $str = preg_replace('/[0-9]+/', '', $str);
 $words = preg_split('/[^0-9A-Za-z\']+/', $str, -1,
 PREG_SPLIT_NO_EMPTY);
 foreach ($words as $w) {
 if (!pspell_check($dict, $w)) {
 $errors[] = $w;
 }
 }
 // if errors exist
 // print error list
 if (sizeof($errors) > 0) {
 echo "The following words were wrongly spelt: " .
 implode(" ", $errors);
 }
 ?>

Continue reading

Popularity: 27% [?]

Comparing Strings for Similarity

You want to compare two strings to see if they sound similar.

<?php
 // compare strings
 // result: "Strings are similar"
 echo (metaphone("rest") == metaphone("reset")) ? 
 "Strings are similar" : "Strings are not similar";
 // result: "Strings are similar"
 echo (metaphone("deep") == metaphone("dip")) ? 
 "Strings are similar" : "Strings are not similar";
 // result: "Strings are not similar"
 echo (metaphone("fire") == metaphone("higher")) ? 
 "Strings are similar" : "Strings are not similar";
 ?>

 

PHP’s metaphone() function—a more accurate version of its soundex()
function—is one of the more unique ones in the PHP string toolkit. Essentially, this
function produces a signature for the way a string sounds; similar-sounding strings

produce the same signature. You can use this property to test two strings to see if
they’re similar—simply calculate the metaphone() keys of each string and see if
they’re the same.

Popularity: 29% [?]

Posted in PHP | Tagged , | Leave a reply

Removing Whitespace from Strings

You want to remove all or some whitespace from a string, or compress multiple
spaces in a string.

<?php
// define string
 $str = " this is a string with lots of embe  dde      d
whitespace ";
 // trim the whitespace at the ends of the string
 // compress the whitespace in the middle of the string
 // result: "this is a string with lots of emb e dd ed whitespace"
 $newStr = ereg_replace('[[:space:]]+', ' ', trim($str));
 echo $newStr;
 ?>

There are two steps involved in performing this task. First, use the trim() function

to delete the unnecessary whitespace from the ends of the string. Next, use the ereg_
replace() function to find multiple whitespace characters in the string and replace
them with a single space. The end result is a string with all extra whitespace removed.
Alternatively, remove all the whitespace from a string, by altering the replacement
string used by ereg_replace(). The following variant illustrates this:

<?php
// define string
 $str = " this is a string with lots of emb e dd
 ed whitespace ";
 // remove all whitespace from the string
 // result: "thisisastringwithlotsofembeddedwhitespace"
 $newStr = ereg_replace('[[:space:]]+', '', trim($str));
 echo $newStr;
 ?>

Popularity: 27% [?]

Posted in PHP | Tagged , , | Leave a reply

Stacks in PHP via Arrays

A stack is a programming data structure that follows the rules of LIFO (Last In First
Out).This is similar to a stack of plates.The last one placed on top of the stack, is the
first one that is going to be taken back off the stack.This logic is used in an RPN calculator,
event handling, state machines such as compilers and interpreters, inventory systems
and many other uses.
PHP provides the basic building blocks of handling stacks via arrays with its
array_push() and array_pop() functions. However, it still takes a little bit of work to
truly treat an array like a stack.

<?php
// A library to implement stacks in PHP via arrays
 // The Initialize function creates a new stack:
 function &stack_initialize() {
 // In this case, just return a new array
 $new = array();
 return $new;
 }
 // The destory function will get rid of a stack
 function stack_destroy(&$stack) {
 // Since PHP is nice to us, we can just use unset
 unset($stack);
 }
 // The push operation on a stack adds a new value onto the top of the stack
 function stack_push(&$stack, $value) {
 // We are just adding a value to the end of the array, so we can use the
 // [] PHP Shortcut for this. It's faster than using array_push
$stack[] = $value;
 }
 // Pop removes the top value from the stack and returns it to you
 function stack_pop(&$stack) {
 // Just use array pop:
 return array_pop($stack);
 }
 // Peek returns a copy of the top value from the stack, leaving it in place
 function stack_peek(&$stack) {
 // Return a copy of the value on top of the stack (the end of the array)
 return $stack[count($stack)-1];
 }
 // Size returns the number of elements in the stack
 function stack_size(&$stack) {
 // Just using count will give the proper number:
 return count($stack);
 }
 // Swap takes the top two values of the stack and switches them
 function stack_swap(&$stack) {
 // Calculate the count:
 $n = count($stack);
 // Only do anything if count is greater than 1
 if ($n > 1) {
 // Now save a copy of the second to last value
 $second = $stack[$n-2];
 // Place the last value in second to last place:
 $stack[$n-2] = $stack[$n-1];
 // And put the second to last, now in the last place:
 $stack[$n-1] = $second;
 }
 }
 // Dup takes the top value from the stack, duplicates it,
 // and adds it back onto the stack
 function stack_dup(&$stack) {
 // Actually rather simple, just reinsert the last value:
 $stack[] = $stack[count($stack)-1];
 }
 // Let's use these to create a small stack of data and manipulate it.
 // Start by adding a few numbers onto it, making it: 73 74 5
$mystack =& stack_initialize();
 stack_push($mystack, 73);
 stack_push($mystack, 74);
 stack_push($mystack, 5);
 // Now duplicate the top, giving us: 73 74 5 5
 stack_dup($mystack);
 // Check the size now, it should be 4
 echo '<p>Stack size is: ', stack_size($mystack), '</p>';
 // Now pop the top, giving us: 5
 echo '<p>Popped off the value: ', stack_pop($mystack), '</p>';
 // Next swap the top two values, leaving us with: 73 5 74
 stack_swap($mystack);
 // Peek at the top element to ensure it is 74
 echo '<p>Current top element is: ', stack_peek($mystack), '</p>';
 // Now destroy it, we are done.
 stack_destroy($mystack);
 ?>

 

Popularity: 29% [?]

Converting Numbers into Roman Numerals

Roman numerals are a great way to add a bit of class to a web page.They are often used
in official titles, such as the XXXIV Pennsic War (34th).The rules for Roman numerals
are straightforward and therefore lend themselves to being scripted.The basic rules of
Roman numerals are
M = 1,000 C = 100 X = 10 I = 1
D = 500 L = 50 V = 5
Simply add up the letters to equal the number you want. Always list the higher numbers
first.The only exception to this rule is that you can place any lower letter in front of a
higher letter to mean minus—for example, IV = 4, IX = 9, XL = 40, XC = 90, CD =
400, and CM = 900.
It should be noted that although other prefix combinations could theoretically be
possible (such as IC to equal 99), these are not normally used and therefore can be
ignored.

<?php
 // A function to return the Roman Numeral, given an integer
 function romanize($num) {
 // Make sure that we only use the integer portion of the value
 $n = intval($num);
 $result = '';
 // Declare a lookup array that we will use to traverse the number:
 $lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
 'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
 'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
// Now, let's work our way through the values, building the string
 // as we go: At each step, divide out the maximum matches at this
 // level, echo out that many characters and then drop the number
 // down to the remainder and repeat:
 foreach ($lookup as $roman => $value) {
 // Determine the number of matches:
 $matches = intval($n / $value);
 // Store that many characters:
 $result .= str_repeat($roman, $matches);
 // Substract that from the number
 $n = $n % $value;
 }
 // The Roman numeral should be built, return it
 return $result;
 }
 // Convert various numbers to Roman Numerals and echo them. Should display:
 // 2005 = MMV
 // 1999 = MCMXCIX
 // 42 = XLII
 echo '<pre>';
 echo "\n 2005 = ", romanize(2005);
 echo "\n 1999 = ", romanize(1999);
 echo "\n 42 = ", romanize(42);
 echo '</pre>';
 ?>

Popularity: 30% [?]

Calculating the Difference Between Two Dates

Finding the number of weeks, days, or even seconds between two dates is something that
programs regularly need to do. Often a database will have powerful built-in procedures
for comparing dates and doing date arithmetic. In PHP, though, you need to handle this
yourself.

<?php
// Set the default timezone to US/Eastern
//date_default_timezone_set('US/Eastern');
// Will return the number of days between the two dates passed in
function count_days($a, $b) {
// First we need to break these dates into their constituent parts:
$a_parts = getdate($a);
$b_parts = getdate($b);
// Now recreate these timestamps, based upon noon on each day
// The specific time doesn't matter but it must be the same each day
$a_new = mktime(12, 0, 0, $a_parts['mon'], $a_parts['mday'], $a_parts['year']);
$b_new = mktime(12, 0, 0, $b_parts['mon'], $b_parts['mday'], $b_parts['year']);
// Subtract these two numbers and divide by the number of seconds in a
// day.Round the result since crossing over a daylight savings time
// barrier will cause this time to be off by an hour or two.
return round(abs($a_new - $b_new) / 86400);
}
// Prepare a few dates
$date1 = strtotime('12/3/1973 8:13am');
$date2 = strtotime('1/15/1974 10:15pm');
$date3 = strtotime('2/14/2005 1:32pm');
// Calculate the differences, they should be 43 & 11353
echo "<p>There are ", count_days($date1, $date2), " days.</p>";
echo "<p>There are ", count_days($date2, $date3), " days.</p>";
?>

 

Popularity: 27% [?]