Jump to content

Array Insert Into Start


JustinK101

Recommended Posts

I was expecting to find a function that inserts a new element to the begging of an array, but I could not locate anything. I need to do the following:

 

myArray[0] = "blah"

myArray[1] = "Blooo"

myArray[2] = "daaa"

 

insert($myArray, 0, 'myNewValue');

 

RESULTS

 

myArray[0] = "myNewValue"

myArray[1] = "blah"

myArray[2] = "Blooo"

myArray[3] = "daaa"

 

This function really should be written into php, but anyway, thanks for the help.

Link to comment
https://forums.phpfreaks.com/topic/37205-array-insert-into-start/
Share on other sites

Ok, my problem just got worse, I have an array that has unique keys and values and I need to not only insert a value but also a key into the start of the array. I tried the following:

 

array_unshft($app_list_strings, 'other_unknown_sic' => 'Other - Unknown');

 

No luck, I dont think array_unshift() allows for inserting key => value.

 

Also, who ever came up with that name needs to be shot, how about just array_insert_start(). Still looking for a simple insert() function that allows you to insert a key => value pair into an array. I thought this would be trivial, php might be lettting me down for once.

FYI for others here is the solution. NOTE this only works if you want to insert at the start. Othwise you are hosed.

 

 

function array_unshift_assoc(&$arr, $key, $val)

{

  $arr = array_reverse($arr, true);

  $arr[$key] = $val;

  $arr = array_reverse($arr, true);

  return count($arr);

}

try something like this:

<?php
        $array = array('red' => 'apples', 'yellow' => 'bananas', 'orange' => 'oranges');

        $array = array_unshift($array, 'purple' => 'grapes');

        print_r($array);
?>

 

that may not work, but the approach may lead to something.

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.