0
<?php
    $interests[50] = array('fav_beverages' => "beer");
?>

now i need the index (i.e. 50 or whatever the index may be) from the value beer.

I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.

please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.

thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer"); $interests[50] = array('fav_cuisine' => "arabic"); $interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.

4
  • var_dump(array_search(array('fav_beverages' => 'beer'), $interests, true)); Commented Apr 5, 2014 at 15:05
  • Why doesn't array_search work for you? $index = array_search('beer', $interests); will set the value of $index to the key index. uk3.php.net/array_search array_search — Searches the array for a given value and returns the corresponding key if successful Commented Apr 5, 2014 at 15:42
  • thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like <?php $interests[50] = array('fav_beverages' => "beer"); ?> Commented Apr 7, 2014 at 5:08
  • @PeeHaa the output is bool(false). Commented Apr 7, 2014 at 8:49

2 Answers 2

2

This should work in your case.

$interests[50] = array('fav_beverages' => "beer");

function multi_array_search($needle, $interests){
    foreach($interests as $interest){
        if (array_search($needle, $interest)){
            return array_search($interest, $interests);
            break;
        }
    }
}

echo multi_array_search("beer", $interests);
Sign up to request clarification or add additional context in comments.

1 Comment

You're calling array_search() twice. This might make it slower for large arrays. It could be improved by doing the assignment inside the if statement.
1

If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:

$needle = 'beer';

foreach ($interests as $index => $arr) {
    foreach ($arr as $value) {
        if ($value == $needle) {
            echo $index;
            break;
        }
    }
}

Demo

1 Comment

Exactly what I'm going to answer. +1

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.