Category Archives: micro tutorial

PHP and MySQL Natural Sort

Use Case

Let’s say we have an array of data represented by some text followed by a number. Just like the movies from a movie series like “Mission Impossible” or “Pirates of the Carribean”. We know that they are often followed by the consecutive number of the episode.

Mission: Impossible 1
Mission: Impossible 2
Mission: Impossible 3
...

Since we have no more than three or four episodes we can easily sort the array if it’s not sorted initially.

$a = array('Mission: Impossible 2', 'Mission: Impossible 3', 'Mission: Impossible 1');
 
sort($a);
 
// Mission: Impossible 1
// Mission: Impossible 2
// Mission: Impossible 3
print_r($a);

However in some cases we can have more than 10 episodes. Then we can meet a problem while sorting the array above.

$a = array('Episode 1', 'Episode 2', 'Episode 11', 'Episode 112');
 
sort($a);
 
// Episode 1
// Episode 11
// Episode 112
// Episode 2
print_r($a);

Now because this is by default an alphabetical sort order we get an array that isn’t sorted to our human undestanding.

Natural Sort
Alphabetical vs. Natural sort order

The question is how to overcome this problem?
Continue reading PHP and MySQL Natural Sort

jQuery UI Slider IE bugfix

Do your jQuery slider brakes under IE too?

When you want to null the sliders on an page, using jQuery UI Slider, somehow the following code works in any browser except IE.

// wrong
$('.my-slider').slider('value', 0);

I say somehow, because according to the documentation this code is simply wrong. It can be used to get the value of the slider as it is a getter. You can null the value with the following snippet.

// correct
$('.my-slider').slider('option', 'value', 0);

IE Fix

Another way to null the value is with an anonymous object.

// correct
$('.my-slider').slider({ value: 0 });

This works on every browser including IE.

How to Setup Different Error Messages for Each Zend Form Element Validator

Anyone who has worked with that has come across this problem. I’d like to show different error message on each validator attached to a Zend_Form_Element. Let’s say we validate an text input field. We want it to contain only digits, but also we’d like to display different messages when the field is empty and when the user has entered something that is different from digits.

It can be done by attaching to the form element two validators: Zend_Validate_Digits and Zend_Validate_NotEmpty, but first let’s see how to change the default “Value is required and can’t be empty” error message of a form field.

$element = $form->createElement('text', 'phone');
$element->setLabel('Please, enter your phone number:')
	->setRequired(true)
	->addValidator('Digits');
$form->addElement($element);

Here we validate the field with Zend_Validate_Digits and we have set it to be required. Thus everything containing characters, i.e. “my123name” or “007bond”, will be false, while “1234” will be true.

Zend Framework
To show different error messages you've to attach them per validator and not per form element!

Continue reading How to Setup Different Error Messages for Each Zend Form Element Validator

PHP: Don’t Call the Destructor Explicitly

“PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++”[1] says the documentation for destructors, but let’s see the following class.

class A
{
	public function __construct()
	{
		echo 'building an object';
	}
 
	public function __destruct()
	{
		echo 'destroying the object';
	}
}
 
$obj = new A();

Well, as you can not call the constructor explicitly:

$obj->__construct();

So we should not call the destructor explicitly:

$obj->__destruct();

The problem is that I’ve seen this many times, but it’s a pity that this won’t destroy the object and it is still a valid PHP code.
Continue reading PHP: Don’t Call the Destructor Explicitly

How to Check if a Date is More or Less Than a Month Ago with PHP

Let’s say we have the following problem: we have to check whether a date is more than a month ago or less than a month ago. Many developers go in the wrong direction by calculating the current month and then subtracting the number of months from it. Of course, this approach is slow and full of risks of allowing bugs. Since, two months before January, which is the first month of the year, is actually November, which is the eleventh month. Because of these pitfalls, this approach is entirely wrong.

strtotime() is a lot more powerful than you think!
strtotime() is a lot more powerful than you think!

The question is whether PHP cannot help us with built-in functions to perform these calculations for us. It is obvious, that from version 5.3.0 and later, there is an OOP section, which is great, but unfortunately this version is still not updated everywhere. So, how to accomplish the task?

The Wrong Approach

As I said, there are many ways to go in the wrong direction. One of them is to subtract 30 days from current date. This is completely wrong, because not every month has 30 days. Here, some developers will begin to predefine arrays to indicate the number of days in each month, which then will be used in their complicated calculations. Here is an example of this wrong approach.

echo date('Y-m-d', strtotime(date('Y-m-d')) - 60*60*24*30);

This line is full of mistakes. First of all strtotime(date(‘Y-m-d’)) can be replaced by the more elegant strtotime(‘now’), but for this later. Another big mistake is that 60*60*24*30, which is number of seconds in 30 days can be predefined as a constant. Eventually the result is wrong, because not every month has 30 days.

The Correct Approach

A small research of the problem and the functions in versions prior of 5.3.0 of PHP is needed. Typical case study of date formatting happen when working with dates from a database. The following code is a classical example. Continue reading How to Check if a Date is More or Less Than a Month Ago with PHP