1

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?

1
  • 1
    What is the default value? Can you just set that to 0 when you create the array? Commented Jun 30, 2011 at 17:05

2 Answers 2

12

Yes, with 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 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 false as booleans with zeroes (this does include the empty string, but it also includes e.g. null values -- so you might want to tweak the condition, depending on your 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);
Sign up to request clarification or add additional context in comments.

5 Comments

Just to be pedantic - this'll still use a loop. It'll just be done invisibly inside PHP instead of explicitly via foreach() or whatever.
You need to be checking for $item['loggedin_time'].
@MarcB: Obviously, but this question strikes me as one with practical applications (keep it short), not theoretical (can this be done without a loop).
@konforce: Why? $input would be $users[$user_id].
@Jon, I assumed he wants to do so for the entire array $users array upfront, but as he's already iterating over that somehow, he might as well just call array_map once per iteration (per your solution).
0

I assume you are retrieving this information from a database of some sort.

If you are getting the array from a Mysql Table try something like this: http://forums.mysql.com/read.php?20,36579,36579#msg-36579

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.