Returning elements from a PHP array using another array

Arrays are extremely handy and very powerful way to handle data. Popular PHP programming language has extensive array functions to manipulate arrays. An array is actually an ordered map what comes to array data type in PHP. Such a map has values that can be associated to keys. In addition to an ordinary vector type list an array can be implemented in many other ways, such as hash table, collection, stack, queue and many more. A value in an array can be of a single data type or another array constructing a multidimensional array.

An array takes any number of comma-separated key-value pairs. A key can be an integer number or a string while the value may be of any type, even another array. The following sample code snippet populates a single array with an array() function found in PHP language.

$arr = array('foo' => 'bar', 8 = true);

This simple line of PHP code sets up an array with two values: 'bar' and true. They both have unique identifier known as a key. In this example the keys are: 'foo' and 8. The value can be returned from an array using the key.

echo $arr['foo']; // returns 'bar' echo $arr[8]; // returns 1 meaning boolean value true

Sometimes I use large arrays and need to quickly return certain values. I could traverse the array in a loop like in this sample:

foreach ($arr as $key => $value) {   if ($key == 'foo') {     echo $value;   } }

Looping the array this way looks very complicated and seems to be slow in performance. The code becomes even more messy when searching for multiple values. The following code returns multiple values from an array.

foreach ($arr as $key => $value) {   if (($key == 'foo') || ($key == 8)) {     echo $value;   } }

The more keys I have to search for the more complicated this code becomes. So I needed another approach to solve the desired functionality. I have created another array to hold the keys to search for and I call this array as $findThese. I could, of course, extend the sample code like this:

$arr['apple'] = 'red'; $arr['plum'] = 'violet'; $arr['grape'] = 'green'; $arr['tomato'] = 'red'; $arr['banana'] = 'yellow'; $findThese = array('plum', 'banana'); $result = array(); foreach ($arr as $key => $value) {   foreach ($findThese as $findThis) {     if ($key == $findThis) {       $result[$key] = $value;     }   } } print_r($result);

Now, this code snippet returns correctly 'violet' and 'yellow', but looks not so sophisticated with all those loops. Using the powerful array functions of PHP this could be accomplished with two simple lines of code:

$findThese = array_flip($findThese); print_r(array_intersect_key($arr, $findThese));

The first line flips the values and keys in $findThese array. By default setting up an array without explicitly assigning the values with keys the values listed become just plain values in the array with default integer keys starting from 0. When using array_intersect_key() function I need an array that has keys to compare with. The array_flip() function swaps the default keys and set values as follows:

$findThese = array('plum', 'banana'); // Array ( [0] => plum [1] => banana )  print_r($findThese); $findThese = array_flip($findThese); // Array ( [plum] => 0 [banana] => 1 ) print_r($findThese);

The $findThese array is now ready to be used with array_intersect_key() function which takes two (or more) parameters. The first parameter is the master array with keys to check. In my case this would the $arr array holding the values to look for. The second parameter is an array to compare keys against to. Again, in this case this is the $findThese array containing the keys to search for. The array_intersect_key() function makes an intersection resulting an array containing all the values of $arr array which have matching keys that are present in $findThese array.

Final words

The array_intersect_key() function is very handy but sometimes overlooked. Understanding mathematics and especially set theory will help implementing the excellent array functions of PHP. The final code gains more performance and maintaining the application becomes easier while staying away from long and complicated loops as shown in the examples. You may set up the key array so that there is no need to use the array_flip() function. I only introduced this function to keep the code even more simplistic.

Julkaistu torstaina 14.5.2009 klo 19:46.

Beethoven - Viulukonsertto