tags:

views:

55

answers:

4

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 can I do that

thanks

A: 

This $array[1] = 5;

dusk
+1  A: 

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;
    }
}
Felix Kling
+1  A: 

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.

karim79
I'd say, `empty` is not the right function here. It will also return true, for `0`, `'0'` and `FALSE` which are very likely not empty values in this case.
Felix Kling
You might be right, I'd say it really depends on the OP's exact requirements. I've edited that in.
karim79
+4  A: 

5.3 version

$arr = array_map(function($n) { return !empty($n) ? $n : 5; }, $arr);
bsboris
Closure and ternary... I'd upvote you twice if I could.
Entendu