Page 1 of 1

Array Help

Posted: Sat Nov 22, 2008 4:55 pm
by PaulSlocun
I'm trying to do the following:

In a loop, I receive integers one by one which I want to append to the end of an array. Occasionally I will need to find a previously entered integer in the array and insert the new value before it, instead of appending it to the end. The first part is no problem -- the second part is where I'm having problems.

I'm kinda getting confused by the hybrid linked-lists/array functionality in PHP, and I've been scouring the array functions trying to figure it out, but everything ends up being very convoluted. I found the array_splice which can be used as an insert function, but I can't figure out how to find the offset of a value that's already been entered into the array.

Re: Array Help

Posted: Sat Nov 22, 2008 5:34 pm
by Syntac

Re: Array Help

Posted: Sat Nov 22, 2008 5:38 pm
by PaulSlocun
array_search() returns the key. array_splice() works from the offset. How do I find out the offset of a key in the array?

Re: Array Help

Posted: Sat Nov 22, 2008 5:44 pm
by Syntac
If you're using a numeric array, key == offset. If not, try this:

Code: Select all

$the_offset = array_search($value_being_searched_for, array_values($the_array));

Re: Array Help

Posted: Mon Nov 24, 2008 10:42 am
by pickle
Unless this is a huge dataset, I'd just use in_array() to find if the value is in the array at all, add the new integer to the end, then sort() the array.