2

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

1
  • Which of those PHP versions are you using? Commented Jun 11, 2010 at 22:11

4 Answers 4

4

5.3 version

$arr = array_map(function($n) { return !empty($n) ? $n : 5; }, $arr);
Sign up to request clarification or add additional context in comments.

Comments

2

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;
    }
}

Comments

1

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.

2 Comments

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.
You might be right, I'd say it really depends on the OP's exact requirements. I've edited that in.
-2

This $array[1] = 5;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.