Main image
23rd December
2010
written by Ricky Stevens

A common technique I use in PHP is to cycle an array and remove the array items which aren’t required for my operation. For instance if I’ve got an array of questions, and I need to remove all the questions that are already answered, as well as removing the questions that have been disabled or are irrelivent for that user, I will go through the question array and unset() the array item. This will leave me an array with only the required questions. Simple enough really, but a side effect of this is that all of the array keys are now foobar’d, so we will need to rebuild the array keys.

Consider the following code:

  1. <?PHP
  2.  
  3.   $arrPossible = array('a','b','c','d','e','f');
  4.  
  5.   $arrDisable = array('a','c','d');
  6.  
  7.   foreach( $arrPossible as $key => $val ) {
  8.     if( in_array( $val, $arrDisable ) ) {
  9.       unset( $arrPossible[ $key ] );
  10.     }
  11.   }
  12.  
  13.   var_export($arrPossible);
  14.  
  15.   /*
  16.    *  array(
  17.    *    1 => 'b'
  18.    *    4 => 'e'
  19.    *    5 => 'f'
  20.    *  )
  21.    */
  22.  
  23. ?>

As you can see, this technique leaves the original array keys in place, meaning they no longer associate the the offset of the array item. The way to rebuild this array and assign new offset keys is to use PHP‘s array_values() function. See the following code:

  1. <?PHP
  2.  
  3.   $arrPossible = array('a','b','c','d','e','f');
  4.  
  5.   $arrDisable = array('a','c','d');
  6.  
  7.   foreach( $arrPossible as $key => $val ) {
  8.     if( in_array( $val, $arrDisable ) ) {
  9.       unset( $arrPossible[ $key ] );
  10.     }
  11.   }
  12.  
  13.   var_export( array_values( $arrPossible ) );
  14.  
  15.   /*
  16.    *  array(
  17.    *    0 => 'b'
  18.    *    1 => 'e'
  19.    *    2 => 'f'
  20.    *  )
  21.    */
  22.  
  23. ?>

Obviously this technique won’t apply to everyone, as many may wish to assign the unmatched array items to a new array. This works if there is only one routine to disable the array items, but when you’re working with a large number of routines to manipulate an array, I find it more efficient to modify the existing array and then rebuild its indexes, than keep creating new arrays.

PHP

1 Comment

  1. max4ever
    22/02/2011

    nice trick, thanks

Leave a Reply