2
$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.

1
  • Added the proper foreach() below. Commented Mar 23, 2016 at 15:02

3 Answers 3

4

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.

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

5 Comments

then how i can make new array which have value no for keys. and then print_r it?
Not getting third value for third key.
when i print_r($new) it shows me original array with blank value for third key.
Don't check $key check $val.
Oops, thanks. Anyway, I'd suggest accepting Rizier's answer.
2

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

2 Comments

@JoelHinz search, replacement and the subject parameter can take an array as argument. Many people don't know this about str_replace() even though it's documented in the manual.
Yeah, I knew about the first two params, but I haven't read the documentation for that function in a very long time. :)
1

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;
}

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.