开发者

change empty array element to a value

i have an array like this Array ([0]=>'some values'[1]=>'')

I want to change the empty elemnt of an array to a value of 5

how 开发者_JAVA百科can I do that

thanks


5.3 version

$arr = array_map(function($n) { return !empty($n) ? $n : 5; }, $arr);


If you know at which position it is, just do:

$array[1] = 5;

If not, loop through it and check with === for value and type equality:

foreach($array as &$element) { //get element as a reference so we can change it
    if($element === '') { // check for value AND type
        $element = 5;
    }
}


You can use array_map for this:

function emptyToFive($value) {
    return empty($value) ? 5 : $value;       
}

$arr = array_map(emptyToFive, $arr);

As of PHP 5.3, you can do:

$func = function($value) {
    return empty($value) ? 5 : $value;       
};
$arr = array_map($func, $arr);

EDIT: If empty does not fit your requirements, you should perhaps change the condition to $value === '' as per @Felix's suggestion.


This $array[1] = 5;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜