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?
Returning index valusefor given array item?
Moderator: General Moderators
Re: Returning index valusefor given array item?
I'm not quite sure what you mean.
To print "Feb":
To get that the index for "Feb" is 2:
To see if the 2nd index is Feb:
To print "Feb":
Code: Select all
echo $months[2];Code: Select all
$key = array_keys($months, 'Feb');
echo $key[0];Code: Select all
echo $months[2] == 'Feb' ? 'true' : 'false';Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Re: Returning index valusefor given array item?
Your second example is what I needed. Many thanks for your reply.
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
Re: Returning index valusefor given array item?
Code: Select all
date('m');
// and
date('M');Re: Returning index valusefor given array item?
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
Edit:Order of arguments are now reversed to be correct
Code: Select all
$key = array_search('Feb',$months);
Last edited by pickle on Mon Jan 28, 2008 9:57 am, edited 1 time in total.
Reason: Order or arguments to array_search() was backwards
Reason: Order or arguments to array_search() was backwards
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Re: Returning index valusefor given array item?
Yes, array_search is much 'cleaner', although the arguments should be reversed.
Thanks for the tip.
Thanks for the tip.