Articles

The month of PHP functions : of keys and values

  • Ecrit par Damien Seguy
  • dimanche 15 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


I tend to use associative arrays quite a lot, to keep values as couples : the key, which is often unique, and a value, which may be anything else. This permits the handling of values by group : values from a MySQL row with their respective column name, liste of club members and their subscription date, a web URL and it's read date, a username and its full description.


Access to each indivdual value is made from the key. If you lost the key, you must use the array_search() function : this function will scan the array and return the first key it encounters. If you just have to check the existence of a value within an array, use in_array(), which will only return true or false.

Tout test a key presence, just use the isset() function. In fact, it is always faster to test presence with isset() than with array_search() or in_array(). To turn a value array into a key array, you may rely on the array_flip() function. Now, this operation is rather expensive, so use it only when you know you're about to make a fairly large number of tests on the array. The best is to create the array directly as a key array, instead of flipping it.

Array of 100000 elements
array_search()         : 6.8990 ms
in_array()             : 6.9160 ms
isset() + array_flip() : 36.9990 ms
isset() only           : 0.0040 ms

array_keys() get the list of keys from an array. array_values() get only the values, which is a way to get rid of the keys (for an associative array), or to reindex the values with a continuous sequence, whenever you punched holes in the index sequence.

To combine back two arrays into one associative array, you can use the newly appointed function array_combine(). Just like this :

<?php
 
 
$t = array('a' => 'A', 'b' => 'B', 'c' => 'C');
$c = array_keys($t);
$v = array_values($t);
 
 
print_r($c);
print_r($v);
 
 
$v[] = 'D';
$c[9] = 'd';
 
 
$t2 = array_combine($c,$v);
print_r($t2);
 
 
?>

As you can see, the keys are totally ignored by array_combine() : this function just report error when the two combined arrays differ by their number of elements. It will not take into account the keys when matching the new array. The keys and values must be in the right order of each array to be well matched.

Keep in mind
array_combine() was introduced in PHP 5.2.0
array_combine() will only glue two arrays into one : it will not make any sorts of transformations based on keys.

< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter