0

My array is built in this format:

$my_array = array(
     1 => array('Pizza','9.99','New_York'),
     2 => array('Chicken Wok','12.49','New_Jersey'),
    ...
);

Then I fetch a database which contains meals.

How can I get the corresponding key of $my_array by knowing only the meal (e.g. my DB contains 'Chicken Wok' and I need to be able to get '2' as the key)?

Please note that I cannot change the structure of $my_array.

1 Answer 1

4

Anything wrong with just doing a foreach loop?

foreach($my_array AS $key => $meal) {
    if($meal[0] == "Chicken Wok") echo "The key is: $key";
}
Sign up to request clarification or add additional context in comments.

3 Comments

I thought there might be a more efficient way of doing it, performance-wise (my array contains about 100 lines and I'm fetching about 20 entries in the DB)
PHP can loop through arrays very efficiently, I don't think it should be a concern. The simple solutions are usually the best.
You could get fancy and write a recursive function that uses array_search(), but ultimately you're still looping through your array until you find a match, it won't save you anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.