Stylized line drawing of mark playing the flute

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.

$a = array(' a ', '   b', '   c   ');$a = array_map('trim', $a);print_r($a);

array_flip

This exchanges all keys with their associated values.

 array **array\_flip** ( array $trans )
$a = array( 'foo' => 1, 'bar' => 2, 'baz' => 3);$b = array_flip($a);print_r($b);
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)

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) . '';

usort($a, 'cmp\_func');
echo ' ' . print_r($a, true) . ' ';

array_slice

Extracts a section of an array.

array **array\_slice** ( array $array , int $offset [, int $length [, bool $preserve\_keys= false ]] )
$a = array( 'a', 'b', 'c', 'd');
$b = array_slice($a, 2);
echo '' . print_r($b,true) . ' ';
> Array
> (
> [1] =\> c
> [2] =\> d
> )

array_sum

This returns the sum of the values in an array.

number **array\_sum** ( array $array )
$a = array(1,2,3,4);
echo array_sum($a);

list

Assign values from an array to individual variables.

void **list** ( mixed $varname [, mixed $... ] )
$a = array( 'a', 'b', 'c');
list($val1, $val2, $val3) = $a;
echo "$val1, $val2, $val3";

// a, b, c