I normalize the output of these functions using this logic:
- Cast the value to an array. If it is not an array already, it will be converted to an array with one element, which is the value it was, e.g.
(array) false
becomesarray (false)
. - Use
array_filter
, which, when not passed a callable, simply filters falsy values from the array.
Here is this logic in action:
foreach (array_filter((array) get_post_meta($id, $meta_key)) as $value) {
// ...
}
Warning: This will strip all falsy values, e.g. if your meta value is zero or an empty string, it will be not be iterated through.