a

PHP

You are browsing the PHP category.

Using numbers to represent data

Posted on October 22nd, 2009 - PHP | 0 Comments

I’m currently in the process of rebuilding one of my older sites from the ground up. One thing that the new version makes use of is a field in several database tables called ’state’. Basically, this holds an integer value ranging from 0 upwards where each number represents a specific meaning. For example…

0: Inactive
1: Active
2: Processed
3: Archived

The reasons for doing this are quite simple; it saves space in the database and is also a lot easier (and nicer) to work with.

Now, previously, when for example I wanted to loop through each row and display the textual meaning of each of the values I would either use a switch statement or a big if-else statement block. Now though I make use of a much simpler method…

1
2
3
4
5
6
7
8
9
function number_state($state = 0, $labels = array())
{
	$text = $labels[$state];
 
	if($text == "")
		$text = "Unknown";
 
	return $text;
}

This function simply takes two parameters. The first is the number itself; the second is an array of the corresponding value meanings. To use it just do this…

1
echo number_state(1, array("State zero", "State one", "State two", "State three"));

Or, in a simple loop…

1
2
3
4
for($i = 0; $i <= 3; $i++)
{
	echo number_state($i, array("State zero", "State one", "State two", "State three"));
}

It’s a nice and simple solution to a simple problem. From my perspective it is much better having something like this compared to big chunks of code doing the same thing.

How to get page number in WordPress

Posted on September 27th, 2009 - PHP, WordPress | 2 Comments

I run quite a few WordPress sites and one of the things I needed to do lately was to get the current page number in WordPress. It can be easily done. To grab the current WordPress page number just use the following.

1
$pageID = (get_query_var('paged')) ? get_query_var('paged') : 1;

And that’s all that’s to it. Then of course you can use simple if statement to do all sorts of things. For example, if you only wanted to display something on the very first page (or 2nd, 3rd, 4th, etc) you can do this.

1
2
3
4
5
6
$pageID = (get_query_var('paged')) ? get_query_var('paged') : 1;
if($pageID == 1):
	// Put your stuff here
	<h2>This is only displayed on the first page</h2>
	<p>Wooooo</p>
endif;

Page numbers are simple in WordPress!