3

I have an indexed array. I process the items from the array and push the processed item into a new associative array. While in process, I leave out some items. I process the items that were left out later, and now I need to add these items into the new array, but I want their positions to be the same as the original array.

Since the first array is indexed and the second is associative, this is a bit tricky.

Examine the following code:

$array1 = [
    "item 1a",
    "item 2k",
    "item 3special",
    "item 4f",
    "item 5v",
];

// process $array1, leave out the special item
// create $array2 with the processed items

$array2 = [
    "a" => "item 1a",
    "k" => "item 2k",
    "f" => "item 4f",
    "v" => "item 5v",
];

// process the special item
// insert the special item into $array2 using its original position in $array1
// ???

Desired output:

$array2 = [
    "a" => "item 1a",
    "k" => "item 2k",
    "s" => "item 3 processed",
    "f" => "item 4f",
    "v" => "item 5v",
];

I've solved the problem by creating a third array, and saving the original position of the array, loop the second array, keep track of index, etc. See below:

$special_item = "item 3special";
$si_processed = "oh, I am so special";
$org_position = array_search($special_item, $array1); // 2

$new_array = [];

$index = 0;
foreach ($array2 as $key => $value) {
    if ($index == $org_position) {
        $array3["s"] = $si_processed;
    }
    $array3[$key] = $value;
    $index++;
}
print_r($array3);

Outputs:

Array
(
    [a] => item 1a
    [k] => item 2k
    [s] => oh, I am so special
    [f] => item 4f
    [v] => item 5v
)

Is there a better way to deal with this, maybe a PHP function that I'm not aware of?


Update: Using the code from the answers to How to insert element into arrays at specific position?, I've put together this function:

function insertAt($array = [], $item = [], $position = 0) {
    $previous_items = array_slice($array, 0, $position, true);
    $next_items     = array_slice($array, $position, NULL, true);
    return $previous_items + $item + $next_items;
}

$org_position = array_search($special_item, $array1); // 2
$array2       = insertAt($array2, ["s" => $si_processed], $org_position);
Community
  • 1
  • 1
akinuri
  • 10,690
  • 10
  • 65
  • 102
  • 3
    http://stackoverflow.com/questions/3353745/how-to-insert-element-into-arrays-at-specific-position possible duplicate :) – Marko Mackic Jul 25 '16 at 23:38
  • @MarkoMackic Damn, and I've looked. Let me check it out. – akinuri Jul 25 '16 at 23:54
  • @MarkoMackic Yep, that question (and the answers) helps. I won't delete my question though. Titles matter. Gonna flag myself for duplicate :) – akinuri Jul 26 '16 at 00:23

0 Answers0