Returning index valusefor given array item?

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
PhpDog
Forum Commoner
Posts: 58
Joined: Mon Jan 14, 2008 10:23 am

Returning index valusefor given array item?

Post 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?
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Returning index valusefor given array item?

Post by s.dot »

I'm not quite sure what you mean.

To print "Feb":

Code: Select all

echo $months[2];
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';
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.
PhpDog
Forum Commoner
Posts: 58
Joined: Mon Jan 14, 2008 10:23 am

Re: Returning index valusefor given array item?

Post by PhpDog »

Your second example is what I needed. Many thanks for your reply.
User avatar
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?

Post by Kieran Huggins »

Code: Select all

date('m');
// and 
date('M');
might be worth a look as well
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Returning index valusefor given array item?

Post 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);
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
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
PhpDog
Forum Commoner
Posts: 58
Joined: Mon Jan 14, 2008 10:23 am

Re: Returning index valusefor given array item?

Post by PhpDog »

Yes, array_search is much 'cleaner', although the arguments should be reversed.

Thanks for the tip.
Post Reply