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;
精彩评论