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.

Link to comment
Share on other sites

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. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.