1

I want modify null values in an array(). I only want to modify, not to clean them.

$arr = array ( 'a' => '', 'b' => 'Apple', 'C' => 'Banana');

I want modify and obtain this:

array(a => 'N', b => Apple, C => 'Banana');

I try array_walk() and array_filter(). But empty values are removed.

And I obtain :

array('b' => 'Apple', 'C' => 'Banana');
1
  • 1
    show your array_walk attempt... Commented Jul 19, 2012 at 12:24

3 Answers 3

3
array_walk($arr, function(&$val)
{
    if($val == null)
    {
        $val = 'N';
    }
});

This code works perfectly fine on my machine.

Sign up to request clarification or add additional context in comments.

9 Comments

and you might also want to add ( || $val == '' )
I think OP meant empty instead of null given his example.
'' in PHP is considered as NULL (of course if we don't compare types), but there is no problem in changing that.
Ok works fine with NULL but not with ''. o_O I'm going to look more closely.
@zourite, if you are using $val === null the interpreter will also check type of the $val (so it has to be "real" NULL). And as @Alex said, you can also use if(empty($val)).
|
1

You can also do like this:

$arr = array ( 'a' => '', 'b' => 'Apple', 'C' => 'Banana' );

foreach ( $arr as $key => $value ) {
    if ( !$value ) $value = 'N';
    $new_arr[ $key ] = $value;
}

print_r( $new_arr );

Output:

Array
(
    [a] => N
    [b] => Apple
    [C] => Banana
)

5 Comments

Why don't you use reference like this: foreach($arr as &$value)?
Why you need that? When you use reference, you don't need $key to change the original array, because simple $value = 'N'; will do that.
I'm not changing the original here, but creating a new one ;)
Aww right. OP asked for modifying original array, so that why I was asking these questions :)
It's better to keep the original somewhere and use a new modified. That way you can always go back to the original values if needed.
0
foreach ($yourArray as $k=>&$v) {
    if (empty($v)) {
        $v = 'N';
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.