Custom Sort Functions – Organizing PHP Arrays

October 8th, 2011

First I am going to demonstrate the use of the php function usort(), and then show an example of how to organize your sorting features. There isn’t much to know about the function but it’s good to practice using it since sorting functions can get pretty complex when needed.

//A function must be defined and it must have 2 arguments
function sort_by_suffix($a, $b){

	$ax = intval(substr($a, 5));

	$bx = intval(substr($b, 5));

	if ($ax == $bx) return 0;

	elseif($a < $b) return -1;

	else return 1;

}

//an array of made up codes with a suffix at the end of each one
$codes = array("G45G-5", "G15G-2", "G11G-1", "G33G-3");

//usort modifies the array rather than returning it.
usort($codes, sort_by_suffix);

That was an example of sorting by a portion of a string. Whatever part of the string after 5 characters that could be made into a number was used as a sortable value. If it couldn’t find sortable values the order would be unpredictable. If the suffixes were all the same it would also be that way.
Read the rest of this entry »

PHP Regular Expression Techniques – Part 2: Characters

October 8th, 2011

Now we turn to a component of regular expressions that cannot be left out. We will be dealing with characters, how to use them, and how to escape them when needed. Regular expressions are explained in the PHP manual, and in this article we are focusing on the type that are Perl compatible, like in the function preg_match. The pattern is the regular expression we are using in each case. Since it uses a slash at the beginning and end, here’s the first thing to understand about characters in patterns: each character has a meaning or function, and escaping the character gives it a different meaning.

preg_replace("/catalog/toys/", "catalog/fun", "http://shop.com/catalog/toys");
//this basically cannot work because of the 2nd slash

preg_replace("/catalog/toys/", "catalog/fun", "http://shop.com/catalog/toys");
//this is correct

Escaping a character, as shown, is usually butting the backslash character before it. It is also normal to put it in front of a double quote or another backslash in a PHP string like that anyway, but in patterns we use it for a various things.

preg_replace("/[rn]/", "", "http://shop.com/catalog/toysn"); //removes the newline

r and n are also standard php string characters representing newlines. (There may be different systems for newlines from different operating systems and programs, some use n only, some use rn.) The [] brackets in the pattern mean you want to match any character inside the brackets. The function basically means replace r or n with “”. If you wanted to actually match brackets instead of that you can escape them too: []
Read the rest of this entry »

Tips for OOP Programming with PHP- Part 2: Object Storage

October 8th, 2011

Before starting this article/tutorial you should already be familiar with PHP, and basic class and object syntax. This article is going to go through some useful operations you can do with objects. The first thing I want to demonstrate is how to store objects and their member variables.

class MyCart{

	var $items;

	function add_item ($artnr, $num){

		$this->items[$artnr] += $num;

	}

}

session_start();

$_SESSION['user_cart'] = new MyCart();

In this case we are storing the object in the session variable. It is a fairly painless process, and getting that stored object on the next page the user loads is just as easy, after session_start() it will be available just like a session variable. If you try to use the session stored object on a page that does not have the class’s declaration, class MyCart{}, you will get a generic object with no member functions, as explained on the PHP manual page ‘Object Serialization’.

$user_cart = new MyCart();

$user_cart_string_data = serialize($user_cart);

$fp = fopen('data.txt', 'w');

fwrite($fp, $user_cart_string_data);

fclose($fp);

This is another basic method of storing objects. We converted the object to a string representation, and made or overwrote a file with that data. If it is not already clear, you restore the object by reading the file into a string, then using unserialize on it, reversing the effects of serialize. Like the session type of storage, you need the class to be defined in any file that uses that type of object.
Read the rest of this entry »

UNIX Timestamp Explained – A PHP Tutorial

October 4th, 2011

Understanding PHP’s date and time functions doesn’t seem difficult, but if you don’t already have a grasp of the UNIX timestamp system you won’t get the most out of them. time() is a PHP function that returns the current UNIX timestamp, which is a number. Specifically, it is the number of “Seconds since the UNIX Epoch (January 1 1970 00:00:00 GMT)”. It is independent of locations/timezones so it makes sense to use it as absolute time for computer and IT purposes and it is a number that can be held in 4 bytes, so it’s easy to store.

echo date ("l dS of F Y h:i:s A", time()); //current date and time
echo date ("l dS of F Y h:i:s A", time() - (60 * 60)); //date and time an hour ago
echo date ("l dS of F Y h:i:s A", time() + (60 * 60 * 24 * 90)); //date and time in 90 days

As you can see time() can be useful for doing simple math to get future or previous values. When stored in a database, the UNIX timestamp can be easily searched and modified, and there are many practical uses for it in programming languages, software, and technology.

To sum it up the UNIX timestamp is just the number of seconds since the start of 1970. This means it cannot hold dates that occurred before that time. In theory there are also future dates that it may not hold, because the programming language isn’t expecting numbers that high. This introduction to PHP’s UNIX timestamp capabilities doesn’t cover every aspect but the common uses have been explained.

PHP Regular Expression Techniques – Part 1: Pattern Modifiers

October 4th, 2011

This article will focus on PHP’s regular expression functions with pattern modifiers. Specifically these functions are of the preg type, and have preg as the prefix. preg_match() is probably the most basic regular expression function of that type and some examples of it will be used in this article.

Regular expressions provide versatile ways of searching text or ‘matching’ it. A string called a pattern is used, similar to a search phrase, and in this case the patterns take a form that is basically the same a the expressions in the Perl language.
Read the rest of this entry »

Tips for OOP Programming with PHP- Part 1: Objects and References

October 3rd, 2011

Programming in PHP utilizing objects is not complex and the syntax and other basics are well covered in various articles and tutorials. It’s also covered in the PHP manual and I will include a brief example for those who need a refresher. Before that I am going to illustrate the basic principals of references without using objects at all. I will then build upon that example to show how use objects and references in your program in useful and efficient ways.
Read the rest of this entry »