JustinK101 Posted February 5, 2007 Share Posted February 5, 2007 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 More sharing options...
JustinK101 Posted February 5, 2007 Author Share Posted February 5, 2007 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. Link to comment https://forums.phpfreaks.com/topic/37205-array-insert-into-start/#findComment-177729 Share on other sites More sharing options...
JustinK101 Posted February 5, 2007 Author Share Posted February 5, 2007 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); } Link to comment https://forums.phpfreaks.com/topic/37205-array-insert-into-start/#findComment-177733 Share on other sites More sharing options...
boo_lolly Posted February 6, 2007 Share Posted February 6, 2007 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. Link to comment https://forums.phpfreaks.com/topic/37205-array-insert-into-start/#findComment-177847 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.