Animals, PHP and HTML:

2 04 2010

Array Manipulation

If you were going to sort an associative array by its keys rather than its values, how would you do this? With PHP there is usually more than one way to achieve a result and this holds true in this case as well. You could use two excellent array handling functions, namely array_flip() and asort().

The output below was generated by using the two array functions on the associative array $animals composed of the following key-value pairs:
array(‘dog’=>”Roxy”, ‘cat’=>’Queenie’, ‘fish’=>’Fred’, ‘snake’=>’Sandra’, ‘lizard’ => ‘Lizzie’)


<?php
// first swap keys with values
$flipped = array_flip($animals);
// then sort but maintain the key associations
if (asort($flipped)) {
// display the associative array in an unordered list
echo '<ul>';
foreach($flipped as $name => $type) {
echo '<li style="list-style:none">' . $type . ' : ' . $name . '</li>';
}
echo '</ul>';
}
?>

This way of doing things however requires that you use two array functions to manipulate the data and the code at first glance may seem somewhat convoluted.

A better approach and one that would speed things up, too, is to use ksort() and avoid having to resort to calling array_flip(). ksort() is a dandy function that will allow you to sort the keys of the array. The code then becomes as simple as the following:

<?php
if ( ksort($animals) ) {
// display the associative array in an unordered list
echo '<ul>';
foreach($animals as $type => $name) {
echo '<li style="list-style:none">' . $type . ' : ' . $name . '</li>';
}
echo '</ul>';
}
?>

Whichever way you wish to proceed, both yield the same result:

cat : Queenie
dog : Roxy
fish : Fred
lizard : Lizzie
snake : Sandra

The question of which to use is best answered by, another question, which bit of code would you prefer to maintain?

This work is licensed under a Creative Commons License
.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: