How to reverse a string

Reversing a string in most languages is a pretty trivial task. In PHP we have a dedicated strrev function to do so: $string = 'This is my awesome string!'; $reverse = strrev($string); But what if this function didn’t exist? How would you go about reversing the string? For me, I’d loop through the string from back to forward build out a new string. You...

Read Full Article →

How to generate a date range

From time to time I need to loop through a date range. One approach is to generate a start date and an end date and then add 1 day to the start date until it reaches the end date (or whatever interval you want to increment by). This works wonders thanks to strtotime: $start = '2014-12-07'; $end = '2014-12-31'; while ($start <= $end) {...

Read Full Article →

How to convert a string to an array

Converting a string to an array is a pretty common task when programming in PHP. If you don’t know much about PHP you could easily fall into a situation where you’re manually looping through each character in a string checking for a delimiter or keeping a counter and assembling strings of the same length and assigning the value to a new array. Fortunately PHP...

Read Full Article →

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 →