Page 1 of 1
Returning index valusefor given array item?
Posted: Fri Jan 25, 2008 4:05 am
by PhpDog
If I have:
$months[1] = "Jan";
$months[2] = "Feb";
$months[3] = "Mar";
how can I ascertain that index 2 pertains to "Feb" in $months please?
Re: Returning index valusefor given array item?
Posted: Fri Jan 25, 2008 4:15 am
by s.dot
I'm not quite sure what you mean.
To print "Feb":
To get that the index for "Feb" is 2:
Code: Select all
$key = array_keys($months, 'Feb');
echo $key[0];
To see if the 2nd index is Feb:
Code: Select all
echo $months[2] == 'Feb' ? 'true' : 'false';
Re: Returning index valusefor given array item?
Posted: Fri Jan 25, 2008 4:17 am
by PhpDog
Your second example is what I needed. Many thanks for your reply.
Re: Returning index valusefor given array item?
Posted: Fri Jan 25, 2008 2:01 pm
by Kieran Huggins
might be worth a look as well
Re: Returning index valusefor given array item?
Posted: Fri Jan 25, 2008 3:58 pm
by pickle
array_keys() works, but I'd use
array_search() instead, as it will return the key as an integer, not an array element.
Edit:Order of arguments are now reversed to be correct
Code: Select all
$key = array_search('Feb',$months);
Re: Returning index valusefor given array item?
Posted: Sat Jan 26, 2008 8:23 am
by PhpDog
Yes, array_search is much 'cleaner', although the arguments should be reversed.
Thanks for the tip.