Saving the world with PHP array functions

I'm not to going to cover all of the PHP array functions but I thought I'd go over a few. I see a lot of code examples online that could be easily be shortened by taking advantage of these functions.

So here are a few interesting ones that might save you some work down the road.

[array_map][]

This applies a callback function to every element of an array and returns the resulting array.

> array **array\_map** ( callback $callback , array $arr1 [, array $... > ] )

For example: Applying the trim function to every element of an array.

~~~~ {.php name="code"} $a = array(' a ', ' b', ' c ');$a = array_map('trim', $a);print_r($a); wzxhzdk:0

>

Array

(

[1] => foo

[2] => bar

[3] => baz

)

usort

This sorts an array by value but uses a custom function for the comparison which is handy if you have an array of objects and you want to sort by some property within those objects. According to the PHP docs, "The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second."

> bool **usort** ( array &$array , callback $cmp\_function )

(To do the same thing by keys instead of values, use uksort)

~~~~ {.php name="code"} function cmp_func($a, $b) { if( $a->val < $b->val ) { return -1; }elseif( $a->val == $b->val ) { return 0; }elseif( $a->val > $b->val ) { return 1; }}class Foo { public $val; public function __construct($val) { $this->val = $val; }}$a = array();$a[] = new Foo(3);$a[] = new Foo(2);$a[] = new Foo(1);echo '' . print_r($a, true) . ' wzxhzdk:1 ';

>

Array

(

[1] => c

[2] => d

)

[array_sum][]

This returns the sum of the values in an array.

> number **array\_sum** ( array $array )

~~~~ {.php name="code"} $a = array(1,2,3,4);echo array_sum($a); wzxhzdk:2

>

a, b, c