tags:

views:

137

answers:

6

Hello,

Let's imagine that we have two arrays

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

$array_2 = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);

Now, I'd like to insert array('sample_key' => 'sample_value') after third element of each array. How can I do it?

Thank you.

+1  A: 

Hi,

Have a look at those slides there are many examples:

http://www.benoist.ch/coursWebProgramming/slides/base/slides-beamer.pdf

have also a look at those source code examples:

http://www.benoist.ch/coursWebProgramming/examples/basic-examples.php

cheers

Daniel

Daniel Gartmann
+1  A: 

In the context of an associative array ($array_2) positioning within the array doesn't make a difference. You'd just add:

$array_2['sample_key'] = 'sample_value';

In a standard array with numbered keys (which is what $array_1 appears to be), you'd do a similar thing:

$array_1[3] = 'sample_value';

Remember, array numbering starts at 0, so position "3" is really the fourth element of the array. This would overwrite whatever you already had listed in position 3, though.

EAMann
Thank you for your answer. About $array_2; I see your point of view, but positioning is really important (especially when you're looping and displaying items from this array). About $array_1; Using $array_1[3] = 'sample_value' will overwrite current value of $array_1[3].
Kirzilla
+1  A: 
function array_insert($arr, $insert, $position) {
    foreach ($arr as $key => $value) {
            if ($i == $position) {
                    foreach ($insert as $ikey => $ivalue) {
                            $ret[$ikey] = $ivalue;
                    }
            }
            $ret[$key] = $value;
            $i++;
    }
    return $ret;
}

doesn't really look handy, but it works.

clausvdb
you're basically trying to do splicing, don't reinvent the wheel.
Paul Dragoonis
Nope, he is not reinventing the wheel. array_splice() do not allow to put key and value. Only value with specific position as key.
Kirzilla
yeah, but as remarked before, array_splice does not support associative arrays. I'd be more than happy to see a more elegant approach.
clausvdb
Your function is really good, but it doesn't work propertly with position bigger than array length ( try executing this array_insert($array_2, array("wow" => "wow"), 4) ). But it can be easily fixed. Your answer is great and you've answered my question!
Kirzilla
+2  A: 

For your first array, use splice:

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

array_splice($array_1, 3, 0, 'more');
print_r($array_1);

output:

Array(
    [0] => zero
    [1] => one
    [2] => two
    [3] => more
    [4] => three
)

for the second one there is no order so you just have to do :

$array_2['more'] = '2.5';
print_r($array_2);

And sort the keys by whatever you want.

M42
+1 Good point that the second array is unordered.
Tomas
The second array does have an order... All arrays have, as they're also double linked lists.
Artefacto
+1  A: 

I recently wrote a function to do something similar to what it sounds like you're attempting, it's a similar approach to clasvdb's answer.

function magic_insert($index,$value,$input_array ) {
  if (isset($input_array[$index])) {
    $output_array = array($index=>$value);
    foreach($input_array as $k=>$v) {
      if ($k<$index) {
        $output_array[$k] = $v;
      } else {
        if (isset($output_array[$k]) ) {
          $output_array[$k+1] = $v;
        } else {
          $output_array[$k] = $v;
        }
      } 
    }

  } else {
    $output_array = $input_array;
    $output_array[$index] = $value;
  }
  ksort($output_array);
  return $output_array;
}

Basically it inserts at a specific point, but avoids overwriting by shifting all items down.

Cags
Try this magic_insert(3, array("wow" => "wow"), $array_2); Take $array_2 from question text.
Kirzilla
I wouldn't expect that to work since $array_2 is associative and the concept of position is generally not relevant in such a situation.
Cags
+1  A: 
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
  'zero'  => '0',
  'one'   => '1',
  'two'   => '2',
  'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
    array("my_key" => "my_value") +
    array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:

Array
(
    [zero] => 0
    [one] => 1
    [two] => 2
    [my_key] => my_value
    [three] => 3
)
Artefacto
This also a good point, but it should be placed into separated function.
Kirzilla
@Kirzilla That's left as an exercise to the reader.
Artefacto