PHP Arrays

Posts about arrays in PHP

PHP Logo

PHP Function To Work Out Average Values In Array

11th March 2008 - 2 minutes read time

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.

function average($array)
{
 $total = 0;
 foreach ($array as $item) {
  $total += $item;
 };
 return $total/count($array);	
}

However, a much simpler way of doing things is just to use the PHP function array_sum(), which adds up all of the values in the array. Because this is done by the PHP engine it should take less time than using a for loop.

function average($array) {
 return array_sum($array) / count($array);
}

Tests show that the second function is only just faster when using short (2 or 3 items) arrays, but the second function is significantly faster when looking at longer (10 or more) arrays.

PHP Logo

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.

function biasedRandom($numbers){
 $total = 0;
 foreach($numbers as $number=>$weight){
  $total += $weight;
  $distribution[$number] = $total;
 };
 $rand = mt_rand(0,$total-1);
 foreach($distribution as $number=>$weights){
  if($rand<$weights){
   return $number;
  };
 };
}

This function is used in the following way.

PHP Logo

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.

PHP Logo

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.

$array1 = array('item1', 'item2');
$array2 = array('item3', 'item4');
$array3 = array_merge($array1, $array2);
print_r($array3);

Will print out.

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

You can also create arrays using the array command inside the parameter list.

PHP Logo

Shuffle An Array In PHP

24th January 2008 - 3 minutes read time

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.

$array = array('one'=>1,'two'=>2);

Would be turned into the following after using shuffle().

Array
(
  [0] => 2
  [1] => 1
)

A way around this is to use the following function, this uses the PHP function array_rand() to extract the all of the keys in the array in a random order before ensuring that the key associations are in place.

PHP Logo

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.

function array_mode($array,$justMode=0) 
{
  $count = array();
  foreach ( $array as $item) {
    if ( isset($count[$item]) ) {
      $count[$item]++;
    }else{
      $count[$item] = 1;
    };
  };
  $mostcommon = '';
  $iter = 0;
  foreach ( $count as $k => $v ) {
    if ( $v > $iter ) {
    $mostcommon = $k;
    $iter = $v;
    };
  };
  if ( $justMode==0 ) {
    return $mostcommon;
  } else {
    return array("mode" => $mostcommon, "count" => $iter);
  }
}

This is used in the following way.

PHP Logo

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.

$array = array(1,34,6,2325,5,34,2);
echo "<pre>";
print_r($array);
echo "</pre>";

Will produce the following result.

Array
(
[0] => 1
[1] => 34
[2] => 6
[3] => 2325
[4] => 5
[5] => 34
[6] => 2
)

Notice the use of the pre tags. This is to allow the output to be properly formatted on screen, otherwise it looks messy. Of course you could just view source, but I find the formatted output easier on the eye. You could also write it out like this: