Get value from array where another value is matched

greg's picture

He has: 1,581 posts

Joined: Nov 2005

An array:

$myarray = array ([0] => ([id] => 1 [name] => greg)
[1] => ([id] => 5 [name] => joe))

What I want to do is get the id from the array where name = $var (obviously I'll set the var)

So

$var = "joe";
$id = where ($myarray[name] == $var)

I'm possibly too tired to see the obvious, or maybe not.. as I also won't specifically have the array key for the array being searched in (eg [0] and [1] in above example).
Maybe I'd at least need to know the top level array key ([0] and [1]) to make this even possible?

I know a foreach is possible, looking like the only possibility atm, but I wanted to avoid a loop if possible as the multi-array in question is huge.

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

If the array is huge, and your array looks like that (it has fields), why aren't you letting a relation databases handle this for you?

Is your array in any particular order? If it is, you would still need a loop, but you could use a binary search to find a name. That would bring search time down a ton.

Another idea, which would use a lot of space, would be to create a parallel array which has the names as keys, and the index (of the other array) as values.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Hmm, I should probably have mentioned (sorry) it's a Wordpress site.
The array is built in the core (I could edit it but wont) and is for a navigation menu.

This is to show breadcrumbs for the current nav position.
The array is in the same order as long as the WP categories remain the same.

I can't really use a binary search as it's a value from a different key I want.
The array is multi dimensional. So I need to search each sub arrays to match a particular key's value but actually get another key's value if matched (same sub array though).

I already have a loop for the nav, and need to get the breadcrumbs prior to looping and showing the nav. I really don't want to loop the same array twice in succession.

Looks a parallel array as you suggested will be the best option here.
Loop to do the breadcrumbs and make a second array. I only use 3 of the values from the huge array anyway so making a second isn't too big of an issue.

I just thought there might be a way to search and match an array value and then get another key's value if matched.
Probably asking too much of the ol' PHP system.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.