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.
$arr = array( 'key1' => 'Label 1', 'key2' => 'Second Label', 'key3' => 0, 'key4' => 'Label No. 4', 'key5' => 0, ); $arr_filtered = array_filter($arr); /* $arr_filtered = array( 'key1' => 'Label 1', 'key2' => 'Second Label', 'key4' => 'Label No. 4', ); */ $arr_filtered_keys = array_keys(array_filter($arr)); /* $arr_filtered_keys = array( 'key1', 'key2', 'key4', ); */
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.