Page 1 of 1

[resolved] more specific in_array

Posted: Thu Jul 05, 2007 9:23 am
by pentascape
Hi All,

Is it possible to make in_array a little more specific when it is searching for values (and keys if we're not being strict) in an array?

Lets take the following array ($array) for example:

Code: Select all

Array
(
[0] => apple
[1] => banana
[2] => pear
[3] => Array
(
[one] => apple
[two] => tree
[three] => stuff
)
)
normally

Code: Select all

in_array('apple',$array);
would return true, but how can I specify it only looks in one type of key, for example the 'one' key?

in pseudo code:
is 'apple' in any key named 'one' anywhere in the array

Posted: Thu Jul 05, 2007 9:28 am
by volka
'apple'==$array['one']

Posted: Thu Jul 05, 2007 10:13 am
by vigge89

Code: Select all

in_array('apple',$array[3]);
???

Oh, missed the last line, nevermind.
Try a foreach loop through the array (and any sub-arrays) and see if it has a key named 'one', and if it does check if it contains 'apple'?

Posted: Thu Jul 05, 2007 10:17 am
by pentascape
Yeh, I did a foreach loop in the end, I just wondered if there was a way of doing it within in_array(). Obviously that function is very simple. I was merely trying to avoid a hefty foreach loop.

Thanks though :)

Posted: Thu Jul 05, 2007 10:22 am
by vigge89
You could use array_keys() with the optional search parameter, but you would still need a loop of some sort for multidimensional arrays, I'd go previous solution though.