Sort an array in reverse order

Arrays are a great way to store / work with data. In PHP, arrays are one of the most powerful data types of available. From time to time, you need to sort an array in reverse order. Of course, PHP has you covered: $array = [ 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', ]; rsort($array); print_r($array);...

Read Full Article →

Pull random values from an array

Like most things, you can solve this problem with a number of different approaches. Without knowing about array_rand in PHP, you could end up doing something like this to pull a random value from an array: $array = ['one', 'two', 'three', 'four', 'five']; shuffle($array); echo $array[0]; The array is shuffled and grabbing the first index yields a random value. If you wanted to pull...

Read Full Article →

Difference between dates

Prior to PHP 5.3 the act of calculating the difference between two dates was a bit more manual than it is now. By manual, I mean there wasn’t a function that existed to aid in the process if by nothing else, the documentation itself. Let’s take a look at how you can caculate the difference (in number of days) between two dates in PHP...

Read Full Article →

Benchmarking PHP code

Have you ever asked yourself, “I wonder which of these blocks of code will run faster?” I know I have and I use a very basic template for setting up these benchmarking experiments. The gist of the script is to run through each block of code n times tracking the amount of time and memory it took to run. It’s not nearly as complete...

Read Full Article →

How to generate the Fibonacci sequence with PHP

The Fibonacci sequence is a sequence of numbers that are derived from the previous numbers in the sequence. The sequence starts at zero and each subsequent number is sum of the previous two numbers in the sequence. There are a number of ways to accomplish this and the most common caveat is to store every single number in the sequence instead of just the...

Read Full Article →