Changing a simple PHP array to an associative one

Arrays are very powerful in PHP scripting language. The language itself provides dozens of useful array functions to work with. A simple array contains just elements, but thorough inspection reveals a lot more behind the scenes. Each element in an array has always a key associated with the element value. Although the programmer does not explicitly set the key, it is automatically generated when creating a simple array. The first example below makes a simple array.

$a = array('one', 'two', 'three', 'four');

Dumping the contents of the variable $a shows the array structure as follows:

print_r($a);

The above example will output:

Array ( [0] => one [1] => two [2] => three [3] => four )

Each element now has a key starting from 0 to 5 expressed in brackets. The actual element value is on the right side of the double arrow notation. Some PHP application frameworks, such as Zend Framework, pass parameters to action methods as part of the web address. The following URL is an example how Show action method in Gallery controller is invoked passing a parameter named "picture" with value 48392 using Zend Framework:

http://www.example.com/gallery/show/picture/48392/ size/medium

Traditionally the address would look like this:

http://www.example.com?method=gallery&action=show& picture=48392&size=medium

When using the parse_url() function of PHP language results in an array with predefined keys.

$p = parse_url('http://www.example.com/gallery/show/ picture/48392/size/medium');

The $p variable now holds an array like this:

Array ( [scheme] => http [host] => www.example.com [path] => /gallery/show/picture/48392/size/medium )

We can now easily split the path element into a separate array.

$a = explode('/', $p['path']);

The first attempt to split the path produces an array with an empty element. This is due to the slash character at the beginning of the string.

Array ( [0] => [1] => gallery [2] => show [3] => picture [4] => 48392 [5] => size [6] => medium )

Adding an array_filter() function removes the empty element.

$a = array_filter(explode('/', $p['path']));

This function only unsets the empty element preserving the keys unaltered. Keys can be automatically renumbered using array_values() function.

$a = array_values( array_filter(explode('/', $p['path'])) );

The $a variable now outputs an array with keys starting from zero:

Array ( [0] => gallery [1] => show [2] => picture [3] => 48392 [4] => size [5] => medium )

I would like to have an array that actually reflects the intended parameter/value pair. Such an array would have every other element as a key as follows:

Array ( [picture] => 48392 [size] => medium )

I start dropping the first three redundant elements as they are the empty element and the controller/action pair. Using the array_slice() function produces a whole new array with keys renumbered.

$a = array_slice(explode('/', $p['path']), 3);

The $a variable now outputs the desired array to continue with:

Array ( [0] => picture [1] => 48392 [2] => size [3] => medium )

The next step flips the keys and elements so that the element value becomes a key and vice versa.

$a = array_flip($a);

This example outputs an array:

Array ( [picture] => 0 [48392] => 1 [size] => 2 [medium] => 3 )

I then filter only elements with even values using a callback function.

$k = array_filter($a, create_function('$x', 'return (!($x % 2));') );

Filtering produces another array in $k variable.

Array ( [picture] => 0 [size] => 2 )

Using the array_keys() function separates only the keys and creates yet another new array, this time having the keys as element values.

$k = array_keys(array_filter($a, create_function('$x', 'return (!($x % 2));')) );

The $k variable has now a new array.

Array ( [0] => picture [1] => size )

Modifying slightly the callback function the following code filters the odd values the same way.

$v = array_filter($a, create_function('$x', 'return ($x % 2);') );

The $v variable now holds an array with odd values only.

Array ( [48392] => 1 [medium] => 3 )

The resulting arrays are starting to look the required outcome, but the value array needs to flip again to switch the keys and values.

$v = array_flip(array_filter($a, create_function('$x', 'return ($x % 2);') ));

This operation creates a useful array in $v variable.

Array ( [1] => 48392 [3] => medium )

The final step is to combine these two arrays. The array_combine() function does the trick and it takes two arrays, one with keys and the other with values.

$c = array_combine($k, $v);

The new $c variable finally outputs the required array of parameter/value pairs, where the parameter name is the key and the parameter value as array element value.

Array ( [picture] => 48392 [size] => medium )

I have finalized the code below to wrap everything up:

$p = parse_url('http://www.example.com/gallery/show/ picture/48392/size/medium'); $a = array_flip(array_slice( explode('/', $p['path']), 3 )); $c = array_combine( array_keys(array_filter($a, create_function('$x', 'return (!($x % 2));'))), array_flip(array_filter($a, create_function('$x', 'return ($x % 2);'))) );

Final words

PHP arrays are extremely handy and easy to work with. Many slow string operations could be avoided by splitting the string into an array and using the vast number of array manipulation functions of the scripting language. With some imagination array functions provide very powerful tools to attain the same effects the endless lines of code do. My example here shows how to turn a simple array to an associative one where every other element forms the key of the element and the rest of the array is used to element values.

Julkaistu Tuesdayna 7.6.2011 klo 18:17 avainsanalla ohjelmointi.

Edellinen
Kivi-juhlien seitsemän veljestä
Seuraava
Viitosen ratikkalinja