Jump to content

simple array manipulation


AudiS2

Recommended Posts

One thing I can think of is it would mean the difference between having to manually echo out things in a specific order and just looping.  Anyways, here's my take:

 

<?php
$array1 = array('color'=>'green', 'size'=>'big');

foreach ($array1 as $key => $val) {
   if ($key == 'size') {
    $newarray['weight'] = 'heavy';
   }
   $newarray[$key] = $val;
}
print_r($newarray);
?>

 

'weight' => 'heavy' is hardcoded into the condition because I don't really know where that's coming from. You'll have to insert your own var there.

Nope, apparently not.  Seems kind of odd that there doesn't seem to be a built-in array_insert function to insert a key=>value or even just value into a specific position of an array, like after or before a specified element.  I figured out a bunch of alternate methods to achieve the same thing, using various other array manipulation functions, but overall, ^^ seemed to be the quickest and simplest method, imo. 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.