Follow Sebastiaan de Jonge on Twitter
Sebastiaan de Jonge

Blog

14Feb

PHP: Extra array functions

Posted on February 14, 2011 in PHP by Sebastiaan de Jonge

During my recent PHP/TYPO3 adventures I had to come up with some extra array functionality to grab my desired data from an array. Shockingly I couldn't find any official PHP way to do this. So I created my own.

Getting the average value of an array 
  1. function array_average($array) {
  2.     $total = count($array);
  3.     $sum = array_sum($array);
  4.  
  5.     return round($sum / $total, 0);
  6. }
function array_average($array) {
    $total = count($array);
    $sum = array_sum($array);

    return round($sum / $total, 0);
}
Getting the minimum value of an array 
  1. function array_minimum($array) {
  2.     sort($array);
  3.     $minimum = array_shift($array);
  4.     return $minimum;
  5. }
function array_minimum($array) {
    sort($array);
    $minimum = array_shift($array);
    return $minimum;
}
Getting the maximum value of an array 
  1. function array_maximum($array) {
  2.     sort($array);
  3.     $maximum = array_pop($array);
  4.     return $maximum;
  5. }
function array_maximum($array) {
    sort($array);
    $maximum = array_pop($array);
    return $maximum;
}

Like I said, I couldn't find any quicker way to do this. Of course if you have any other suggestions, they are more than welcome.

Comments (3)

  1. Gravatar: AlexAlexon February 16, 2011
    at 10:11
    Reply to this comment

    Yes there are functions that do this

    http://php.net/manual/en/function.max.php
    http://php.net/manual/en/function.min.php

    As for your average function, it doesn't seem there is a standard PHP function for this.

  2. Gravatar: Sebastiaan de JongeSebastiaan de Jongeon February 16, 2011
    at 10:58

    RE: Yes there are functions that do this

    Hi Alex,

    Thanks for the contribution. The min() and max() versions are indeed more versatile. Unfortunately one does not always know where to look. As I looked through the array functions it's no mystery why I didn't find them, as they are listed under the math functions :-)

    Cheers,
    Sebastiaan

  3. Gravatar: noonenooneon February 4, 2012
    at 13:36
    Reply to this comment

    moving average

    regarding the average function, it _might_ be faster to calculate the average as the array is being built, rather than calculating it at the end, thus elimating the need for the function entirely.

Got something to say?

 
Notify me when someone adds another comment to this post
 

Search

Categories

Tags

Archive

Blogroll

Syndicate