Array Help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
PaulSlocun
Forum Newbie
Posts: 2
Joined: Sat Nov 22, 2008 4:33 pm

Array Help

Post 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.
User avatar
Syntac
Forum Contributor
Posts: 327
Joined: Sun Sep 14, 2008 7:59 pm

Re: Array Help

Post by Syntac »

PaulSlocun
Forum Newbie
Posts: 2
Joined: Sat Nov 22, 2008 4:33 pm

Re: Array Help

Post 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?
User avatar
Syntac
Forum Contributor
Posts: 327
Joined: Sun Sep 14, 2008 7:59 pm

Re: Array Help

Post 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));
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Array Help

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply