Sadia Mehjabin
Sadia Mehjabin

Reputation: 129

Create associative array from foreach values

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

Upvotes: 1

Views: 1927

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

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
}

Upvotes: 1

Related Questions