PHP Arrays

Posts about arrays in PHP

Biased Random Value From Array With PHP

10th March 2008 - 1 minute read time

Sometimes you will want to get a random value form an array in a biased random way, that is, you will want certain values to be returned more than others. Here is a function that will generate a single key from an array, with a greater change of a higher value being retrieved.

Getting All Permutations Of An Array In PHP

29th February 2008 - 3 minutes read time

Here are two ways in which you can figure out all of the different permutations of an array.

The first is using a recursive algorithm. This nibbles apart the array and sticks it back together again, eventually resulting in all of the different permutations available.

Append One Array To Another In PHP

12th February 2008 - 2 minutes read time

Appending arrays in PHP can be done with the array_merge() function. The array will take any number of arrays as arguments and will return a single array. Here is an example using just two arrays.

Shuffle An Array In PHP

24th January 2008 - 3 minutes read time

To randomise an array in PHP use the shuffle() function like this.

  1. $array = range(1, 5);
  2. shuffle($array); // randomise array

There are two limitations to this function. The first is that it completely removes any key association that you may have set up. So the following array.

PHP Array Mode Function

7th January 2008 - 2 minutes read time

The following mode function will return the most commonly occurring value from an array of values, also called the mode. If just the array is used then only the most commonly occurring value will be returned. The second parameter can be used to return an array containing the mode and the number of times that this value occurs in the array.

Printing Arrays Using print_r()

20th December 2007 - 2 minutes read time

When debugging PHP code the print_r can be useful if you want to know what an array or object contains. It will take any variable as input and will print off as much information as it can about that variable. The following code.