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.
Array Help
Moderator: General Moderators
-
PaulSlocun
- Forum Newbie
- Posts: 2
- Joined: Sat Nov 22, 2008 4:33 pm
Re: Array Help
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
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
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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.