1

I want to create associative array from foreach loop.

    if (sizeof($ads) > 0) {
    foreach($ads as $social_item) {
        $sdbr .= $social_item['sidebar'];
        $pno .= $social_item['no']; 
       }
       echo $sdbr // cow hen
       echo $pno  // milk egg
    }

How can I create associative array like this one?

$out = array("cow"=>"milk","hen"=>"egg");
3
  • Keep in mind that if you do this, any duplicate values of 'sidebar' will be overwritten in the $out array. It will end up with only the last associated 'no' value. Commented Jul 17, 2017 at 21:27
  • 1
    @Don'tPanic: In this example the only other things I can think of are cow=>steak,hen=>breast Commented Jul 17, 2017 at 21:29
  • No problem, the value of sidebar and no values are unique. Commented Jul 17, 2017 at 21:29

1 Answer 1

1

Use sidebar as the key and no as the value:

foreach($ads as $social_item) {
    $sdbr = $social_item['sidebar'];
    $pno  = $social_item['no'];
    $out[$sdbr] = $pno;
   }
}
print_r($out);

If you still need the strings:

foreach($ads as $social_item) {
    $sdbr .= $social_item['sidebar'];
    $pno  .= $social_item['no'];
    $out[$social_item['sidebar']] = $social_item['no'];
   }
   echo $sdbr // cow hen
   echo $pno  // milk egg
}
Sign up to request clarification or add additional context in comments.

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.