Working out the average of a bunch of values is quite a common task, but rather than looping through the array, adding together values as you go and the using the count() function to find out the average at the end.
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.
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.
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.
To randomise an array in PHP use the shuffle() function like this.
- $array = range(1, 5);
- 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.
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.
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.