简体   繁体   中英

Replacing null values in PHP array

A common question, but other answers aren't always clear, so I apologise if this has cropped up elsewhere a million times.

Simple; I have null values returning in my array from a query, I want to cycle through and replace them with zero. I've been trying with the following code;

$stat = $db->getUserStats($id, $code, $mod1, $mod2);    
        foreach ($stat as $key => $value) {
            if ($value == null) {
                $value = 0;
            }
        };

Use a reference:

foreach ($stat as $key => &$value) {

The $value you currently have in if ($value == null) is not the actual array value, but a copy created by foreach .

You should unset the reference after the foreach loop. (See the Warning box in the foreach documentation .)


Another possible way to accomplish this is to use an expression in your query to returns zeroes instead of nulls. That will vary depending on which database you're using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM