Reputation: 2436
$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.
Upvotes: 2
Views: 75
Reputation: 59701
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);
Upvotes: 2
Reputation: 25414
It's probably easiest to just run a foreach loop by reference, like this:
foreach ($array as $key => &$val) {
if ($key == '') {
$val = 'No';
}
}
The &
means that you assign the value by reference, so it can be assigned from right within the loop.
Edit: Since you want a new array instead, you can easily do this:
$new = array();
foreach ($array as $key => $val) {
if ($val == '') {
$val = 'No';
}
$new[$key] = $val;
}
That way, you just go through the first array and create a new one on-the-fly.
Upvotes: 4
Reputation: 79024
I love the str_replace()
but since you mentioned array_map()
:
$newfirstarray = array_map(function($v){ return empty($v) ? 'No' : $v; }, $firstarray);
The proper foreach()
would be:
foreach ($firstarray as $key => $val) {
$newfirstarray[$key] = empty($val) ? 'No' : $val;
}
Upvotes: 1