I’m working with a large array. We’re displaying all fields of data in the array with a table. Some fields in the array are null because the user hasn’t accumulated anything in that field. However, we wanted a zero for when they have such a result. Our solution was to display the value along with intval()
intval(@$users[$user_id]['loggedin_time'])
Which is fine, but it is ugly and inelegant. Is there a way, without a foreach loop, to set all values of ” in the array to be 0?
Yes, with
array_map:The above example uses facilities of PHP >= 5.3 (inline anonymous function declaration and the short form of the ternary operator), but you can do the same in any PHP version (only perhaps more verbosely).
You should think a bit about the conditional inside the callback function; the one I ‘m using here will replace all values that evaluate to
falseas booleans with zeroes (this does include the empty string, but it also includes e.g.nullvalues — so you might want to tweak the condition, depending on your needs).Update: PHP < 5.3 version
It’s either this:
Or this: