Search code examples
phparraysmultidimensional-array

Put Values in Multidimensional Array keys


$firstarray = array("first"=>'pakistan',"second"=>'bangladesh',"third"=>'');

I have array like above some keys have value and some keys don't have value. so i want to search this array and place no for those keys which don't have value.

The result which i want:

$newfirstarray = array("first"=>'pakistan',"second"=>'bangladesh',"third"=>'No');

I search on the web find functions like array_filter() , array_map(). i don't know either it work with this

My Little Try

$firstarray = array("first"=>'pakistan',"second"=>'bangladesh',"third"=>'');


foreach($firstarray as $keyx){
    if($keyx==''){
        $keyx='no'; //sorry for this example, at this point i don't know how to put values.
        print_r($firstarray );
    }
}

This code shows me original array and not putting no as a value for third key.


Solution

  • Loop through your array and check if the value is equal to "" if yes replace it with no:

    $result = array_map(function($v){$v == "" ? "no" : $v;}, $array);