Category Archives: PHP

It’s Not True that PHP Arrays are Copied by Value

PHP, Arrays & Passing by Reference

Do you know that objects in PHP5 are passed by reference, while arrays and other scalar variables are passed by value? Yes, you know it, but it’s not exactly true. Let’s see some example and let’s try to answer few questions.

// depending on the machine but both lines return
// expectedly equal values: 331208
 
// 331208
echo memory_get_usage();
echo memory_get_usage();

These two lines of code, expectedly return the same value (in my case 331208), which shows us that because nothing happened in between them the memory usage isn’t growing. Let’s now put some code in between them.

echo memory_get_usage(); // 331616
$a = 10;
echo memory_get_usage(); // 331696

Continue reading It’s Not True that PHP Arrays are Copied by Value

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

Computer Algorithms: Determine if a Number is Prime

Introduction

Each natural number that is divisible only by 1 and itself is prime. Prime numbers appear to be more interesting to humans than other numbers. Why is that and why prime numbers are more important than the numbers that are divisible by 2, for instance? Perhaps the answer is that prime numbers are largely used in cryptography, although they were interesting for the ancient Egyptians and Greeks (Euclid has proved that the prime numbers are infinite circa 300 BC). The problem is that there is not a formula that can tell us which is the next prime number, although there are algorithms that check whether a given natural number is prime. It’s very important these algorithms to be very effective, especially for big numbers.

Overview

As I said each natural number that is divisible only by 1 and itself is prime. That means that 2 is the first prime number and 1 is not considered prime. It’s easy to say that 2, 3, 5 and 7 are prime numbers, but what about 983? Well, yes 983 is prime, but how do we check that? If we want to know whether n is prime the very basic approach is to check every single number between 2 and n. It’s kind of a brute force.

Implementation

The basic implementation in PHP for the very basic (brute force) approach is as follows.

Unfortunately this is one very ineffective algorithm. We don’t have to check every single number between 1 and n, it’s enough to check only the numbers between 1 and n/2-1. If we find such a divisor that will be enough to say that n isn’t prime.

Although that code above optimizes a lot our first prime checker, it’s clear that for large numbers it won’t be very effective. Indeed checking against the interval [2, n/2 -1] isn’t the optimal solution. A better approach is to check against [2, sqrt(n)]. This is correct, because if n isn’t prime it can be represented as p*q = n. Of course if p > sqrt(n), which we assume can’t be true, that will mean that q < sqrt(n).

Beside that these implementations shows how we can find prime number, they are a very good example of how an algorithm can be optimized a lot with some small changes.

Sieve of Eratosthenes

Although the sieve of Eratosthenes isn’t the exact same approach (to check whether a number is prime) it can give us a list of prime numbers quite easily. To remove numbers that aren’t prime, we start with 2 and we remove every single item from the list that is divisible by two. Then we check for the rest items of the list, as shown on the picture below.

http://www.stoimen.com/blog/wp-content/uploads/2012/05/SieveofEratosthenes.png

The PHP implementation of the Eratosthenes sieve isn’t difficult.

Application

As I said prime numbers are widely used in cryptography, so they are always of a greater interest in computer science. In fact every number can be represented by the product of two prime numbers and that fact is used in cryptography as well. That’s because if we know that number, which is usually very very big, it is still very difficult to find out what are its prime multipliers. Unfortunately the algorithms in this article are very basic and can be handy only if we work with small numbers or if our machines are tremendously powerful. Fortunately in practice there are more complex algorithms for finding prime numbers. Such are the sieves of Euler, Atkin and Sundaram.

PHP Strings Don’t Need Quotes

I bet you didn’t know that PHP strings don’t need quotes! Indeed PHP developers work with strings with either single or double quotes, but actually in some cases you don’t need them.

PHP by Book

Here’s how PHP developer declare a string, which is something very common in any programming language.

$my_var = 'hello world';
// or
$my_var = "hello world";

PHP Tricks

What if you do the following:

echo hello;

That appears to be correct … Well, it’s not absolutely correct. You’ll be “noticed”.

// Notice: Use of undefined constant hello
echo hello;

However if you disable error reporting, the code will be completely fine.

error_reporting(0);
 
// no problem now
echo hello;

Variations

What follows from the thing above is that you can use strings without quotes:

// hello
echo hello;
 
// hello world (concatenated)
echo hello . ' world';
 
// helloworld
echo hello . world;

However you can’t have spaces and most of the “special” symbols.

// syntax error
echo hello world;
 
// syntax error
echo hello!;

Final Words

Although you can do this in PHP, that is completely wrong. The code becomes more difficult to read and understand. In the second place you can miss a $ sign in front of a variable declaration and thus the PHP interpreter will assume this is a string. So disable error reporting isn’t so great sometimes.

Computer Algorithms: Insertion Sort

Overview

Sorted data can dramatically change the speed of our program, therefore sorting algorithms are something quite special in computer science. For instance searching in a sorted list is faster than searching in an unordered list.

There are two main approaches in sorting – by comparing the elements and without comparing them. A typical algorithm from the first group is insertion sort. This algorithm is very simple and very intuitive to implement, but unfortunately it is not so effective compared to other sorting algorithms as quicksort and merge sort. Indeed insertion sort is useful for small sets of data with no more than about 20 items.

Insertion sort it is very intuitive method of sorting items and we often use it when we play card games. In this case the player often gets an unordered set of playing cards and intuitively starts to sort it. First by taking a card, making some comparisons and then putting the card on the right position.

So let’s say we have an array of data. In the first step the array is unordered, but we can say that it consists of two sub-sets: sorted and unordered, where on the first step the only item in the sorted sub-set is its first item. If the length of the array is n the algorithm is considered completed in n-1 steps. On each step our sorted subset is growing with one item. The thing is that we take the first item from the unordered sub-set and with some comparisons we put it into its place in the sorted sub-set, like on the diagram bellow.

Main principle of insertion sort
Main principle of insertion sort.

Continue reading Computer Algorithms: Insertion Sort