Archive: January 2009

php function of the day

Fairly often in Drupal I get handed arrays that have significant keys, but the values are either a label or false-y. I generally don't care about the items with empty values, or I specifically want to remove them. The solution is to use array_filter($arr) to remove any array items with false-y values. In fact, sometimes I don't even care about the labels at all, in which case I might do array_keys(array_filter($arr)). Examples below.

  1. $arr = array(
  2.   'key1' => 'Label 1',
  3.   'key2' => 'Second Label',
  4.   'key3' => 0,
  5.   'key4' => 'Label No. 4',
  6.   'key5' => 0,
  7. );
  8.  
  9. $arr_filtered = array_filter($arr);
  10. /*
  11.    $arr_filtered = array(
  12.      'key1' => 'Label 1',
  13.      'key2' => 'Second Label',
  14.      'key4' => 'Label No. 4',
  15.    );
  16. */
  17.  
  18. $arr_filtered_keys = array_keys(array_filter($arr));
  19. /*
  20.    $arr_filtered_keys = array(
  21.      'key1',
  22.      'key2',
  23.      'key4',
  24.    );
  25. */

array_filter() can also take a callback as the second argument, which lets you filter out items on your own terms. See the array_filter() documentation.

flat footing

My aunt shared these two "flat footing" videos on facebook: