PHP - set all empty or null in an array, to 0, without a foreach loop -
i'm working large array. we're displaying fields of data in array table. fields in array null because user hasn't accumulated in field. however, wanted 0 when have such result. our solution display value along intval()
intval(@$users[$user_id]['loggedin_time'])
which fine, ugly , inelegant. there way, without foreach loop, set values of '' in array 0?
yes, array_map
:
$input = array(...); $output = array_map(function($item) { return $item ?: 0; }, $input);
the above example uses facilities of php >= 5.3 (inline anonymous function declaration , short form of ternary operator), can same in php version (only perhaps more verbosely).
you should think bit conditional inside callback function; 1 'm using here replace values evaluate false
booleans zeroes (this include empty string, includes e.g. null
values -- might want tweak condition, depending on needs).
update: php < 5.3 version
it's either this:
function callback($item) { return $item == false ? 0 : $item; } $output = array_map('callback', $input);
or this:
$output = array_map( create_function('$item', 'return $item == false ? 0 : $item;'), $input);
Comments
Post a Comment