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
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
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.
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.