-1

Possible Duplicate:
Search and replace inside an associative array

I think this may have been asked before. But I just want a simple solution.

I have an array like this:

  Array (   "name" => "Krish",
            "age" => "27",
            "COD" => ""
        )

I want to replace "" with "0"

Its a multidimentional array. The return value should be array too.

Edit: I tried preg_replace and str_replace. For some reason, these did not work for me.

Community
  • 1
  • 1
Kevin Rave
  • 13,876
  • 35
  • 109
  • 173
  • 2
    Start writing code. If you can't get it to work, come back and ask again. If you are just looking for a hint to get started, you need to loop through the array(s) and replace any values of `""` with `0`. – AndrewR Apr 24 '12 at 16:48
  • @Kevin Rave preg_replace and str_replace are used for strings whereas you are using an array. you should either convert it to string. or loop the array and manipulate it according to your requirement. consider my example below – Ibrahim Azhar Armar Apr 24 '12 at 16:49

4 Answers4

1
$array = array(
    "name" => "Krish",
    "age" => "27",
    "COD" => ""
);

you may loop the array and repalce what you want

foreach($array as $key => $value)
{
    if($value == "") $array[$key] = 0;
}

Note:

if you know what key is it you can do it like this

$array['cod'] = 0;
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
1
$entry = array("name" => "Krish",
               "age" => "27",
               "COD" => "");
$arr = array_filter($entry, 'valcheck');
print_r($entry); //ORIGINAL ARRAY
print_r($arr); //MODIFIED ARRAY
function valcheck($var)
{
    if($var === "")
        return 0;
    else
        return $var;
}
maiorano84
  • 11,574
  • 3
  • 35
  • 48
0

if your array is $array:

$array['COD'] = "0";
Dave Kiss
  • 10,289
  • 11
  • 53
  • 75
0
<?php
$arr=array(
    "name" => "Krish",
    "age" => "27",
    "COD" => ""
);

print_r(array_map(function($i){return (''===$i)?0:$i;},$arr));
?>
stewe
  • 41,820
  • 13
  • 79
  • 75