zourite
zourite

Reputation: 304

Modify empty values in array

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');

Upvotes: 1

Views: 202

Answers (3)

user1454661
user1454661

Reputation:

foreach ($yourArray as $k=>&$v) {
    if (empty($v)) {
        $v = 'N';
    }
}

Upvotes: 0

Peon
Peon

Reputation: 8030

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
)

Upvotes: 1

mdziekon
mdziekon

Reputation: 3627

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

This code works perfectly fine on my machine.

Upvotes: 3

Related Questions