PHP multidimensional array search by value










247















I have an array where I want to search the uid and get the key of the array.



Examples



Assume we have the following 2-dimensional array:



$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);


The function call search_by_uid(100) (uid of first user) should return 0.



The function call search_by_uid(40489) should return 2.



I tried making loops, but I want a faster executing code.










share|improve this question
























  • interestingly the underscore (and lowdash) librarires add this function to javascript...

    – ErichBSchulz
    Mar 7 '14 at 12:37






  • 6





    I wrote a script to test the performance of a few of the answers. It generates a 500k-member array of arrays and searches through it for a value in the last member. I compared a function like the accepted answer, to the two array_column one-liner answers. I modified them all to return the actual discovered array, not just the key, because usually that's my use case. The function method scored 0.361, search-col 0.184 and keys-col 0.189 average micro delay over 1000 runs for each method.

    – Josh
    Feb 14 '16 at 12:49















247















I have an array where I want to search the uid and get the key of the array.



Examples



Assume we have the following 2-dimensional array:



$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);


The function call search_by_uid(100) (uid of first user) should return 0.



The function call search_by_uid(40489) should return 2.



I tried making loops, but I want a faster executing code.










share|improve this question
























  • interestingly the underscore (and lowdash) librarires add this function to javascript...

    – ErichBSchulz
    Mar 7 '14 at 12:37






  • 6





    I wrote a script to test the performance of a few of the answers. It generates a 500k-member array of arrays and searches through it for a value in the last member. I compared a function like the accepted answer, to the two array_column one-liner answers. I modified them all to return the actual discovered array, not just the key, because usually that's my use case. The function method scored 0.361, search-col 0.184 and keys-col 0.189 average micro delay over 1000 runs for each method.

    – Josh
    Feb 14 '16 at 12:49













247












247








247


75






I have an array where I want to search the uid and get the key of the array.



Examples



Assume we have the following 2-dimensional array:



$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);


The function call search_by_uid(100) (uid of first user) should return 0.



The function call search_by_uid(40489) should return 2.



I tried making loops, but I want a faster executing code.










share|improve this question
















I have an array where I want to search the uid and get the key of the array.



Examples



Assume we have the following 2-dimensional array:



$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);


The function call search_by_uid(100) (uid of first user) should return 0.



The function call search_by_uid(40489) should return 2.



I tried making loops, but I want a faster executing code.







php






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 25 '17 at 22:11









angoru

3,28311117




3,28311117










asked Jul 12 '11 at 8:41









RachitRachit

1,2592107




1,2592107












  • interestingly the underscore (and lowdash) librarires add this function to javascript...

    – ErichBSchulz
    Mar 7 '14 at 12:37






  • 6





    I wrote a script to test the performance of a few of the answers. It generates a 500k-member array of arrays and searches through it for a value in the last member. I compared a function like the accepted answer, to the two array_column one-liner answers. I modified them all to return the actual discovered array, not just the key, because usually that's my use case. The function method scored 0.361, search-col 0.184 and keys-col 0.189 average micro delay over 1000 runs for each method.

    – Josh
    Feb 14 '16 at 12:49

















  • interestingly the underscore (and lowdash) librarires add this function to javascript...

    – ErichBSchulz
    Mar 7 '14 at 12:37






  • 6





    I wrote a script to test the performance of a few of the answers. It generates a 500k-member array of arrays and searches through it for a value in the last member. I compared a function like the accepted answer, to the two array_column one-liner answers. I modified them all to return the actual discovered array, not just the key, because usually that's my use case. The function method scored 0.361, search-col 0.184 and keys-col 0.189 average micro delay over 1000 runs for each method.

    – Josh
    Feb 14 '16 at 12:49
















interestingly the underscore (and lowdash) librarires add this function to javascript...

– ErichBSchulz
Mar 7 '14 at 12:37





interestingly the underscore (and lowdash) librarires add this function to javascript...

– ErichBSchulz
Mar 7 '14 at 12:37




6




6





I wrote a script to test the performance of a few of the answers. It generates a 500k-member array of arrays and searches through it for a value in the last member. I compared a function like the accepted answer, to the two array_column one-liner answers. I modified them all to return the actual discovered array, not just the key, because usually that's my use case. The function method scored 0.361, search-col 0.184 and keys-col 0.189 average micro delay over 1000 runs for each method.

– Josh
Feb 14 '16 at 12:49





I wrote a script to test the performance of a few of the answers. It generates a 500k-member array of arrays and searches through it for a value in the last member. I compared a function like the accepted answer, to the two array_column one-liner answers. I modified them all to return the actual discovered array, not just the key, because usually that's my use case. The function method scored 0.361, search-col 0.184 and keys-col 0.189 average micro delay over 1000 runs for each method.

– Josh
Feb 14 '16 at 12:49












21 Answers
21






active

oldest

votes


















365














function searchForId($id, $array) 
foreach ($array as $key => $val)
if ($val['uid'] === $id)
return $key;


return null;



This will work. You should call it like this:



$id = searchForId('100', $userdb);


It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.



Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.



$key = array_search('100', array_column($userdb, 'uid'));


Here is documentation: http://php.net/manual/en/function.array-column.php.






share|improve this answer




















  • 4





    You should also be able to do this without PHP 5.5 in a one liner using array_map in place of array_column. Just replace array_column($userdb, 'uid') with array_map(function($v)return $v['uid'];,$userdb)

    – Jesse Green
    Feb 23 '16 at 18:12











  • Yea, you are right. Lambda functions are available since PHP 5.3. and better is array_search, isn't it?

    – Jakub Truneček
    Feb 25 '16 at 12:43











  • @angoru I think the original solution (the foreach loop) will perform faster because it stops as soon as a match is found. The newer solution has to iterate through the whole array once to extract array_column, then loop through it a second time to perform the search (until it finds a match). The newer solution is easier to read, more concise, but the OP specifically brought up performance as an issue

    – BeetleJuice
    Jul 27 '17 at 17:19












  • @JakubTruneček . I have something to do with the same array given in the question. I want user's name from the array by passing id. Function findUserName(40489) should return 'Michael'. How its possible?

    – Ashok Gujjar
    Aug 31 '18 at 6:40











  • @JakubTruneček Hi i have faced this problem in my code but i have quite different thing. In my case 'uid' value present multiple times so i need to get an arrays of founded key.

    – Bhavin Thummar
    Sep 25 '18 at 11:54



















232














If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.



If you want just one result:



$key = array_search(40489, array_column($userdb, 'uid'));


For multiple results



$keys = array_keys(array_column($userdb, 'uid'), 40489);


In case you have an associative array as pointed in the comments you could make it with:



$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);


If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!



Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!






share|improve this answer

























  • what if the value I am searching(in this example is 40489) appears more that one time and I want to get all the keys that it appears?

    – Dimitris Papageorgiou
    May 15 '15 at 9:13






  • 2





    i've edit the post to include multiple results.

    – angoru
    May 19 '15 at 4:28











  • if the value 40489 appears more then once in the array will the function return an array of keys ... ?? @angoru

    – jishan
    May 19 '15 at 8:23






  • 1





    This did not work for me when the key in the $userdb did not start as 0,1, 2 etc.. and say the key are 1234,4566 etc. The resulting keys after the array_search are always 0,1,2 and so on

    – Kaushtuv
    Apr 11 '16 at 6:41







  • 1





    This won't work with an associative array, however you can get around that like so: array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))

    – John Mellor
    Jun 2 '17 at 5:53


















24














Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):



function searcharray($value, $key, $array) 
foreach ($array as $k => $val)
if ($val[$key] == $value)
return $k;


return null;



Usage: $results = searcharray('searchvalue', searchkey, $array);






share|improve this answer

























  • This is very helpful, I feel like I'm on the cusp of solving my problem using this solution but I'm still having some issue. Could you perhaps provide insight? The question can be found here: stackoverflow.com/questions/28704644/…

    – jasenmp
    Feb 25 '15 at 0:15


















15














I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.



Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.



Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.



 /**
* @param array multidimensional
* @param string value to search for, ie a specific field name like name_first
* @param string associative key to find it in, ie field_name
*
* @return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search)
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value)
if ($cur_value[$key_to_search] == $search_value)
$keys = $key;


return $keys;



Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.



This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).



/**
* @param array multidimensional
* @param string $search_value The value to search for, ie a specific 'Taylor'
* @param string $key_to_search The associative key to find it in, ie first_name
* @param string $other_matching_key The associative key to find in the matches for employed
* @param string $other_matching_value The value to find in that matching associative key, ie true
*
* @return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null)
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value)
if ($cur_value[$key_to_search] == $search_value)
if (isset($other_matching_key) && isset($other_matching_value))
if ($cur_value[$other_matching_key] == $other_matching_value)
$keys = $key;

else
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys = $key;



return $keys;



Use of function



$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);

$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);


Result



Array ( [0] => 2 ) 





share|improve this answer
































    8














    I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:



     $arr = array(
    'XXX'=>array(
    'YYY'=> array(
    'AAA'=> array(
    'keyN' =>'value1'
    )
    ),
    'ZZZ'=> array(
    'BBB'=> array(
    'keyN' => 'value2'
    )
    )
    //.....
    )
    );


    $result = searchItemsByKey($arr,'keyN');

    print '<pre>';
    print_r($result);
    print '<pre>';
    // OUTPUT
    Array
    (
    [0] => value1
    [1] => value2
    )


    Function code:



    function searchItemsByKey($array, $key)

    $results = array();

    if (is_array($array))

    if (isset($array[$key]) && key($array)==$key)
    $results = $array[$key];

    foreach ($array as $sub_array)
    $results = array_merge($results, searchItemsByKey($sub_array, $key));


    return $results;






    share|improve this answer
































      7














      In later versions of PHP (>= 5.5.0) you can use this one-liner:



      $key = array_search('100', array_column($userdb, 'uid'));





      share|improve this answer
































        4














        Looks array_filter will be suitable solution for this...



        $userdb=Array
        (
        (0) => Array
        (
        (uid) => '100',
        (name) => 'Sandra Shush',
        (url) => 'urlof100'
        ),

        (1) => Array
        (
        (uid) => '5465',
        (name) => 'Stefanie Mcmohn',
        (pic_square) => 'urlof100'
        ),

        (2) => Array
        (
        (uid) => '40489',
        (name) => 'Michael',
        (pic_square) => 'urlof40489'
        )
        );


        PHP Code



        <?php 
        $search = 5465;
        $found = array_filter($userdb,function($v,$k) use ($search)
        return $v['uid'] => $search;
        )

        $values= print_r(array_value($found));
        $keys = print_r(array_keys($found));





        share|improve this answer

























        • @BEJAM SHIVA PRASAD could you please help me out with this stackoverflow.com/questions/44721195/… ?

          – Valay
          Jun 23 '17 at 13:38











        • shows an error :syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ';'

          – Shihas
          Apr 11 '18 at 11:21












        • Can you please paste more info I mean which line and your code and array structure.

          – BEJGAM SHIVA PRASAD
          Apr 12 '18 at 4:01


















        3














        Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.



        function searchArrayKeyVal($sKey, $id, $array) 
        foreach ($array as $key => $val)
        if ($val[$sKey] == $id)
        return $key;


        return false;



        Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.



         // Array Data Of Users
        $userdb = array (
        array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
        array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
        array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
        );

        // Obtain The Key Of The Array
        $arrayKey = searchArrayKeyVal("uid", '100', $userdb);
        if ($arrayKey!==false)
        echo "Search Result: ", $userdb[$arrayKey]['name'];
        else
        echo "Search Result can not be found";



        PHP Fiddle Example






        share|improve this answer

























        • Another reason i use SOF... easier to google and find my own code or something i remember.. +1 for my own public repository

          – Mayhem
          Feb 18 '15 at 23:38











        • BTW, you are setting the result to null and then in the code, you are comparing it to false.

          – Taha Paksu
          Jun 20 '16 at 21:16











        • Corrected with returning false instead, but null might be better incase of checking for booleans

          – Mayhem
          Jun 21 '16 at 0:46


















        2














        Here is one liner for the same,



        $pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];





        share|improve this answer























        • Thanks.. This is what I exactly need.

          – Dolly
          May 3 '18 at 9:35











        • welcome mate!!!

          – Rahul Meshram
          May 7 '18 at 8:55


















        1














        I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:



        function search_in_array_r($needle, $array) 
        $found = array();
        foreach ($array as $key => $val)
        if ($val[1] == $needle)
        array_push($found, $val[1]);


        if (count($found) != 0)
        return $found;
        else
        return null;






        share|improve this answer
































          1














          /**
          * searches a simple as well as multi dimension array
          * @param type $needle
          * @param type $haystack
          * @return boolean
          */
          public static function in_array_multi($needle, $haystack)
          $needle = trim($needle);
          if(!is_array($haystack))
          return False;

          foreach($haystack as $key=>$value)
          if(is_array($value))
          if(self::in_array_multi($needle, $value))
          return True;
          else
          self::in_array_multi($needle, $value);

          else
          if(trim($value) === trim($needle))//visibility fix//
          error_log("$value === $needle setting visibility to 1 hidden");
          return True;



          return False;






          share|improve this answer
































            1














            you can use this function ;
            https://github.com/serhatozles/ArrayAdvancedSearch



            <?php 
            include('ArraySearch.php');

            $query = "a='Example World' and b>='2'";

            $Array = array(
            'a' => array('d' => '2'),
            array('a' => 'Example World','b' => '2'),
            array('c' => '3'), array('d' => '4'),
            );

            $Result = ArraySearch($Array,$query,1);

            echo '<pre>';
            print_r($Result);
            echo '</pre>';

            // Output:
            // Array
            // (
            // [0] => Array
            // (
            // [a] => Example World
            // [b] => 2
            // )
            //
            // )





            share|improve this answer
































              1














              $a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

              $found = null;
              $search = 'eee';

              array_walk($a, function ($k, $v) use ($search, &$found)
              if (in_array($search, $k))
              $found = $v;

              );

              var_dump($found);





              share|improve this answer






























                1














                I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not



                $arr = array(
                array(
                'title' => 'abc'
                )
                );


                Then i can use this



                $res = array_search('abc', array_column($arr, 'title'));
                if($res == '')
                echo 'exists';
                else
                echo 'notExists';



                I think This is the Most simple way to define






                share|improve this answer






























                  1














                  Just share, maybe can like this.



                  if( ! function_exists('arraySearchMulti'))
                  function arraySearchMulti($search,$key,$array,$returnKey=false)

                  foreach ($array as $k => $val)
                  if (isset($val[$key]))
                  if ((string)$val[$key] == (string)$search)
                  return ($returnKey ? $k : $val);

                  else
                  return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);


                  return null;






                  share|improve this answer






























                    0














                    Try this also



                    function search_in_array($srchvalue, $array)

                    if (is_array($array) && count($array) > 0)

                    $foundkey = array_search($srchvalue, $array);
                    if ($foundkey === FALSE)

                    foreach ($array as $key => $value)

                    if (is_array($value) && count($value) > 0)

                    $foundkey = search_in_array($srchvalue, $value);
                    if ($foundkey != FALSE)
                    return $foundkey;



                    else
                    return $foundkey;







                    share|improve this answer






























                      0














                      for( $i =0; $i < sizeof($allUsers); $i++)

                      $NEEDLE1='firstname';
                      $NEEDLE2='emailAddress';
                      $sterm='Tofind';
                      if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])



                      Print_r($resultsMatched); //will give array for matched values even partially matched


                      With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.






                      share|improve this answer

























                      • Please add a phrase to explain why this answers the question

                        – Lorenz Meyer
                        Feb 27 '15 at 15:41











                      • whit help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question

                        – sandeep sharma
                        Feb 27 '15 at 17:16


















                      0














                      Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:



                       function searchArrayKeyVal($sKey, $id, $array) 
                      foreach ($array as $key => $val)
                      if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false)
                      return $key;


                      return false;



                      For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"






                      share|improve this answer
































                        0














                        Try this



                        <?php
                        function recursive_array_search($needle,$haystack)
                        foreach($haystack as $key=>$value)
                        $current_key=$key;
                        if($needle===$value OR (is_array($value) &&
                        recursive_array_search($needle,$value) !== false))
                        return $current_key;


                        return false;

                        ?>





                        share|improve this answer
































                          0














                          $search1 = 'demo';
                          $search2 = 'bob';
                          $arr = array('0' => 'hello','1' => 'test','2' => 'john','3' => array('0' => 'martin', '1' => 'bob'),'4' => 'demo');
                          foreach ($arr as $value)
                          if (is_array($value))
                          if (in_array($search2, $value))
                          echo "successsfully";
                          //execute your code

                          else
                          if ($value == $search1)
                          echo "success";








                          share|improve this answer
































                            0














                            If question i.e.



                            $a = [
                            [
                            "_id" => "5a96933414d48831a41901f2",
                            "discount_amount" => 3.29,
                            "discount_id" => "5a92656a14d488570c2c44a2",
                            ],
                            [
                            "_id" => "5a9790fd14d48879cf16a9e8",
                            "discount_amount" => 4.53,
                            "discount_id" => "5a9265b914d488548513b122",
                            ],
                            [
                            "_id" => "5a98083614d488191304b6c3",
                            "discount_amount" => 15.24,
                            "discount_id" => "5a92806a14d48858ff5c2ec3",
                            ],
                            [
                            "_id" => "5a982a4914d48824721eafe3",
                            "discount_amount" => 45.74,
                            "discount_id" => "5a928ce414d488609e73b443",
                            ],
                            [
                            "_id" => "5a982a4914d48824721eafe55",
                            "discount_amount" => 10.26,
                            "discount_id" => "5a928ce414d488609e73b443",
                            ],
                            ];


                            Ans:



                            function searchForId($id, $array) 
                            $did=0;
                            $dia=0;
                            foreach ($array as $key => $val)
                            if ($val['discount_id'] === $id)
                            $dia +=$val['discount_amount'];
                            $did++;


                            if($dia != '')
                            echo $dia;
                            var_dump($did);

                            return null;
                            ;
                            print_r(searchForId('5a928ce414d488609e73b443',$a));





                            share|improve this answer






























                              21 Answers
                              21






                              active

                              oldest

                              votes








                              21 Answers
                              21






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes









                              365














                              function searchForId($id, $array) 
                              foreach ($array as $key => $val)
                              if ($val['uid'] === $id)
                              return $key;


                              return null;



                              This will work. You should call it like this:



                              $id = searchForId('100', $userdb);


                              It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.



                              Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.



                              $key = array_search('100', array_column($userdb, 'uid'));


                              Here is documentation: http://php.net/manual/en/function.array-column.php.






                              share|improve this answer




















                              • 4





                                You should also be able to do this without PHP 5.5 in a one liner using array_map in place of array_column. Just replace array_column($userdb, 'uid') with array_map(function($v)return $v['uid'];,$userdb)

                                – Jesse Green
                                Feb 23 '16 at 18:12











                              • Yea, you are right. Lambda functions are available since PHP 5.3. and better is array_search, isn't it?

                                – Jakub Truneček
                                Feb 25 '16 at 12:43











                              • @angoru I think the original solution (the foreach loop) will perform faster because it stops as soon as a match is found. The newer solution has to iterate through the whole array once to extract array_column, then loop through it a second time to perform the search (until it finds a match). The newer solution is easier to read, more concise, but the OP specifically brought up performance as an issue

                                – BeetleJuice
                                Jul 27 '17 at 17:19












                              • @JakubTruneček . I have something to do with the same array given in the question. I want user's name from the array by passing id. Function findUserName(40489) should return 'Michael'. How its possible?

                                – Ashok Gujjar
                                Aug 31 '18 at 6:40











                              • @JakubTruneček Hi i have faced this problem in my code but i have quite different thing. In my case 'uid' value present multiple times so i need to get an arrays of founded key.

                                – Bhavin Thummar
                                Sep 25 '18 at 11:54
















                              365














                              function searchForId($id, $array) 
                              foreach ($array as $key => $val)
                              if ($val['uid'] === $id)
                              return $key;


                              return null;



                              This will work. You should call it like this:



                              $id = searchForId('100', $userdb);


                              It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.



                              Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.



                              $key = array_search('100', array_column($userdb, 'uid'));


                              Here is documentation: http://php.net/manual/en/function.array-column.php.






                              share|improve this answer




















                              • 4





                                You should also be able to do this without PHP 5.5 in a one liner using array_map in place of array_column. Just replace array_column($userdb, 'uid') with array_map(function($v)return $v['uid'];,$userdb)

                                – Jesse Green
                                Feb 23 '16 at 18:12











                              • Yea, you are right. Lambda functions are available since PHP 5.3. and better is array_search, isn't it?

                                – Jakub Truneček
                                Feb 25 '16 at 12:43











                              • @angoru I think the original solution (the foreach loop) will perform faster because it stops as soon as a match is found. The newer solution has to iterate through the whole array once to extract array_column, then loop through it a second time to perform the search (until it finds a match). The newer solution is easier to read, more concise, but the OP specifically brought up performance as an issue

                                – BeetleJuice
                                Jul 27 '17 at 17:19












                              • @JakubTruneček . I have something to do with the same array given in the question. I want user's name from the array by passing id. Function findUserName(40489) should return 'Michael'. How its possible?

                                – Ashok Gujjar
                                Aug 31 '18 at 6:40











                              • @JakubTruneček Hi i have faced this problem in my code but i have quite different thing. In my case 'uid' value present multiple times so i need to get an arrays of founded key.

                                – Bhavin Thummar
                                Sep 25 '18 at 11:54














                              365












                              365








                              365







                              function searchForId($id, $array) 
                              foreach ($array as $key => $val)
                              if ($val['uid'] === $id)
                              return $key;


                              return null;



                              This will work. You should call it like this:



                              $id = searchForId('100', $userdb);


                              It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.



                              Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.



                              $key = array_search('100', array_column($userdb, 'uid'));


                              Here is documentation: http://php.net/manual/en/function.array-column.php.






                              share|improve this answer















                              function searchForId($id, $array) 
                              foreach ($array as $key => $val)
                              if ($val['uid'] === $id)
                              return $key;


                              return null;



                              This will work. You should call it like this:



                              $id = searchForId('100', $userdb);


                              It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.



                              Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.



                              $key = array_search('100', array_column($userdb, 'uid'));


                              Here is documentation: http://php.net/manual/en/function.array-column.php.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 23 '17 at 12:10









                              Community

                              11




                              11










                              answered Jul 12 '11 at 8:44









                              Jakub TrunečekJakub Truneček

                              4,97721327




                              4,97721327







                              • 4





                                You should also be able to do this without PHP 5.5 in a one liner using array_map in place of array_column. Just replace array_column($userdb, 'uid') with array_map(function($v)return $v['uid'];,$userdb)

                                – Jesse Green
                                Feb 23 '16 at 18:12











                              • Yea, you are right. Lambda functions are available since PHP 5.3. and better is array_search, isn't it?

                                – Jakub Truneček
                                Feb 25 '16 at 12:43











                              • @angoru I think the original solution (the foreach loop) will perform faster because it stops as soon as a match is found. The newer solution has to iterate through the whole array once to extract array_column, then loop through it a second time to perform the search (until it finds a match). The newer solution is easier to read, more concise, but the OP specifically brought up performance as an issue

                                – BeetleJuice
                                Jul 27 '17 at 17:19












                              • @JakubTruneček . I have something to do with the same array given in the question. I want user's name from the array by passing id. Function findUserName(40489) should return 'Michael'. How its possible?

                                – Ashok Gujjar
                                Aug 31 '18 at 6:40











                              • @JakubTruneček Hi i have faced this problem in my code but i have quite different thing. In my case 'uid' value present multiple times so i need to get an arrays of founded key.

                                – Bhavin Thummar
                                Sep 25 '18 at 11:54













                              • 4





                                You should also be able to do this without PHP 5.5 in a one liner using array_map in place of array_column. Just replace array_column($userdb, 'uid') with array_map(function($v)return $v['uid'];,$userdb)

                                – Jesse Green
                                Feb 23 '16 at 18:12











                              • Yea, you are right. Lambda functions are available since PHP 5.3. and better is array_search, isn't it?

                                – Jakub Truneček
                                Feb 25 '16 at 12:43











                              • @angoru I think the original solution (the foreach loop) will perform faster because it stops as soon as a match is found. The newer solution has to iterate through the whole array once to extract array_column, then loop through it a second time to perform the search (until it finds a match). The newer solution is easier to read, more concise, but the OP specifically brought up performance as an issue

                                – BeetleJuice
                                Jul 27 '17 at 17:19












                              • @JakubTruneček . I have something to do with the same array given in the question. I want user's name from the array by passing id. Function findUserName(40489) should return 'Michael'. How its possible?

                                – Ashok Gujjar
                                Aug 31 '18 at 6:40











                              • @JakubTruneček Hi i have faced this problem in my code but i have quite different thing. In my case 'uid' value present multiple times so i need to get an arrays of founded key.

                                – Bhavin Thummar
                                Sep 25 '18 at 11:54








                              4




                              4





                              You should also be able to do this without PHP 5.5 in a one liner using array_map in place of array_column. Just replace array_column($userdb, 'uid') with array_map(function($v)return $v['uid'];,$userdb)

                              – Jesse Green
                              Feb 23 '16 at 18:12





                              You should also be able to do this without PHP 5.5 in a one liner using array_map in place of array_column. Just replace array_column($userdb, 'uid') with array_map(function($v)return $v['uid'];,$userdb)

                              – Jesse Green
                              Feb 23 '16 at 18:12













                              Yea, you are right. Lambda functions are available since PHP 5.3. and better is array_search, isn't it?

                              – Jakub Truneček
                              Feb 25 '16 at 12:43





                              Yea, you are right. Lambda functions are available since PHP 5.3. and better is array_search, isn't it?

                              – Jakub Truneček
                              Feb 25 '16 at 12:43













                              @angoru I think the original solution (the foreach loop) will perform faster because it stops as soon as a match is found. The newer solution has to iterate through the whole array once to extract array_column, then loop through it a second time to perform the search (until it finds a match). The newer solution is easier to read, more concise, but the OP specifically brought up performance as an issue

                              – BeetleJuice
                              Jul 27 '17 at 17:19






                              @angoru I think the original solution (the foreach loop) will perform faster because it stops as soon as a match is found. The newer solution has to iterate through the whole array once to extract array_column, then loop through it a second time to perform the search (until it finds a match). The newer solution is easier to read, more concise, but the OP specifically brought up performance as an issue

                              – BeetleJuice
                              Jul 27 '17 at 17:19














                              @JakubTruneček . I have something to do with the same array given in the question. I want user's name from the array by passing id. Function findUserName(40489) should return 'Michael'. How its possible?

                              – Ashok Gujjar
                              Aug 31 '18 at 6:40





                              @JakubTruneček . I have something to do with the same array given in the question. I want user's name from the array by passing id. Function findUserName(40489) should return 'Michael'. How its possible?

                              – Ashok Gujjar
                              Aug 31 '18 at 6:40













                              @JakubTruneček Hi i have faced this problem in my code but i have quite different thing. In my case 'uid' value present multiple times so i need to get an arrays of founded key.

                              – Bhavin Thummar
                              Sep 25 '18 at 11:54






                              @JakubTruneček Hi i have faced this problem in my code but i have quite different thing. In my case 'uid' value present multiple times so i need to get an arrays of founded key.

                              – Bhavin Thummar
                              Sep 25 '18 at 11:54














                              232














                              If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.



                              If you want just one result:



                              $key = array_search(40489, array_column($userdb, 'uid'));


                              For multiple results



                              $keys = array_keys(array_column($userdb, 'uid'), 40489);


                              In case you have an associative array as pointed in the comments you could make it with:



                              $keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);


                              If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!



                              Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!






                              share|improve this answer

























                              • what if the value I am searching(in this example is 40489) appears more that one time and I want to get all the keys that it appears?

                                – Dimitris Papageorgiou
                                May 15 '15 at 9:13






                              • 2





                                i've edit the post to include multiple results.

                                – angoru
                                May 19 '15 at 4:28











                              • if the value 40489 appears more then once in the array will the function return an array of keys ... ?? @angoru

                                – jishan
                                May 19 '15 at 8:23






                              • 1





                                This did not work for me when the key in the $userdb did not start as 0,1, 2 etc.. and say the key are 1234,4566 etc. The resulting keys after the array_search are always 0,1,2 and so on

                                – Kaushtuv
                                Apr 11 '16 at 6:41







                              • 1





                                This won't work with an associative array, however you can get around that like so: array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))

                                – John Mellor
                                Jun 2 '17 at 5:53















                              232














                              If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.



                              If you want just one result:



                              $key = array_search(40489, array_column($userdb, 'uid'));


                              For multiple results



                              $keys = array_keys(array_column($userdb, 'uid'), 40489);


                              In case you have an associative array as pointed in the comments you could make it with:



                              $keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);


                              If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!



                              Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!






                              share|improve this answer

























                              • what if the value I am searching(in this example is 40489) appears more that one time and I want to get all the keys that it appears?

                                – Dimitris Papageorgiou
                                May 15 '15 at 9:13






                              • 2





                                i've edit the post to include multiple results.

                                – angoru
                                May 19 '15 at 4:28











                              • if the value 40489 appears more then once in the array will the function return an array of keys ... ?? @angoru

                                – jishan
                                May 19 '15 at 8:23






                              • 1





                                This did not work for me when the key in the $userdb did not start as 0,1, 2 etc.. and say the key are 1234,4566 etc. The resulting keys after the array_search are always 0,1,2 and so on

                                – Kaushtuv
                                Apr 11 '16 at 6:41







                              • 1





                                This won't work with an associative array, however you can get around that like so: array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))

                                – John Mellor
                                Jun 2 '17 at 5:53













                              232












                              232








                              232







                              If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.



                              If you want just one result:



                              $key = array_search(40489, array_column($userdb, 'uid'));


                              For multiple results



                              $keys = array_keys(array_column($userdb, 'uid'), 40489);


                              In case you have an associative array as pointed in the comments you could make it with:



                              $keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);


                              If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!



                              Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!






                              share|improve this answer















                              If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.



                              If you want just one result:



                              $key = array_search(40489, array_column($userdb, 'uid'));


                              For multiple results



                              $keys = array_keys(array_column($userdb, 'uid'), 40489);


                              In case you have an associative array as pointed in the comments you could make it with:



                              $keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);


                              If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!



                              Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Oct 25 '17 at 22:06

























                              answered Jul 2 '14 at 9:08









                              angoruangoru

                              3,28311117




                              3,28311117












                              • what if the value I am searching(in this example is 40489) appears more that one time and I want to get all the keys that it appears?

                                – Dimitris Papageorgiou
                                May 15 '15 at 9:13






                              • 2





                                i've edit the post to include multiple results.

                                – angoru
                                May 19 '15 at 4:28











                              • if the value 40489 appears more then once in the array will the function return an array of keys ... ?? @angoru

                                – jishan
                                May 19 '15 at 8:23






                              • 1





                                This did not work for me when the key in the $userdb did not start as 0,1, 2 etc.. and say the key are 1234,4566 etc. The resulting keys after the array_search are always 0,1,2 and so on

                                – Kaushtuv
                                Apr 11 '16 at 6:41







                              • 1





                                This won't work with an associative array, however you can get around that like so: array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))

                                – John Mellor
                                Jun 2 '17 at 5:53

















                              • what if the value I am searching(in this example is 40489) appears more that one time and I want to get all the keys that it appears?

                                – Dimitris Papageorgiou
                                May 15 '15 at 9:13






                              • 2





                                i've edit the post to include multiple results.

                                – angoru
                                May 19 '15 at 4:28











                              • if the value 40489 appears more then once in the array will the function return an array of keys ... ?? @angoru

                                – jishan
                                May 19 '15 at 8:23






                              • 1





                                This did not work for me when the key in the $userdb did not start as 0,1, 2 etc.. and say the key are 1234,4566 etc. The resulting keys after the array_search are always 0,1,2 and so on

                                – Kaushtuv
                                Apr 11 '16 at 6:41







                              • 1





                                This won't work with an associative array, however you can get around that like so: array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))

                                – John Mellor
                                Jun 2 '17 at 5:53
















                              what if the value I am searching(in this example is 40489) appears more that one time and I want to get all the keys that it appears?

                              – Dimitris Papageorgiou
                              May 15 '15 at 9:13





                              what if the value I am searching(in this example is 40489) appears more that one time and I want to get all the keys that it appears?

                              – Dimitris Papageorgiou
                              May 15 '15 at 9:13




                              2




                              2





                              i've edit the post to include multiple results.

                              – angoru
                              May 19 '15 at 4:28





                              i've edit the post to include multiple results.

                              – angoru
                              May 19 '15 at 4:28













                              if the value 40489 appears more then once in the array will the function return an array of keys ... ?? @angoru

                              – jishan
                              May 19 '15 at 8:23





                              if the value 40489 appears more then once in the array will the function return an array of keys ... ?? @angoru

                              – jishan
                              May 19 '15 at 8:23




                              1




                              1





                              This did not work for me when the key in the $userdb did not start as 0,1, 2 etc.. and say the key are 1234,4566 etc. The resulting keys after the array_search are always 0,1,2 and so on

                              – Kaushtuv
                              Apr 11 '16 at 6:41






                              This did not work for me when the key in the $userdb did not start as 0,1, 2 etc.. and say the key are 1234,4566 etc. The resulting keys after the array_search are always 0,1,2 and so on

                              – Kaushtuv
                              Apr 11 '16 at 6:41





                              1




                              1





                              This won't work with an associative array, however you can get around that like so: array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))

                              – John Mellor
                              Jun 2 '17 at 5:53





                              This won't work with an associative array, however you can get around that like so: array_search(40489, array_combine(array_keys($userdb), array_column($userdb, 'uid')))

                              – John Mellor
                              Jun 2 '17 at 5:53











                              24














                              Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):



                              function searcharray($value, $key, $array) 
                              foreach ($array as $k => $val)
                              if ($val[$key] == $value)
                              return $k;


                              return null;



                              Usage: $results = searcharray('searchvalue', searchkey, $array);






                              share|improve this answer

























                              • This is very helpful, I feel like I'm on the cusp of solving my problem using this solution but I'm still having some issue. Could you perhaps provide insight? The question can be found here: stackoverflow.com/questions/28704644/…

                                – jasenmp
                                Feb 25 '15 at 0:15















                              24














                              Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):



                              function searcharray($value, $key, $array) 
                              foreach ($array as $k => $val)
                              if ($val[$key] == $value)
                              return $k;


                              return null;



                              Usage: $results = searcharray('searchvalue', searchkey, $array);






                              share|improve this answer

























                              • This is very helpful, I feel like I'm on the cusp of solving my problem using this solution but I'm still having some issue. Could you perhaps provide insight? The question can be found here: stackoverflow.com/questions/28704644/…

                                – jasenmp
                                Feb 25 '15 at 0:15













                              24












                              24








                              24







                              Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):



                              function searcharray($value, $key, $array) 
                              foreach ($array as $k => $val)
                              if ($val[$key] == $value)
                              return $k;


                              return null;



                              Usage: $results = searcharray('searchvalue', searchkey, $array);






                              share|improve this answer















                              Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):



                              function searcharray($value, $key, $array) 
                              foreach ($array as $k => $val)
                              if ($val[$key] == $value)
                              return $k;


                              return null;



                              Usage: $results = searcharray('searchvalue', searchkey, $array);







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 23 '17 at 12:02









                              Community

                              11




                              11










                              answered Jul 12 '13 at 17:04









                              reflexivreflexiv

                              1,30211623




                              1,30211623












                              • This is very helpful, I feel like I'm on the cusp of solving my problem using this solution but I'm still having some issue. Could you perhaps provide insight? The question can be found here: stackoverflow.com/questions/28704644/…

                                – jasenmp
                                Feb 25 '15 at 0:15

















                              • This is very helpful, I feel like I'm on the cusp of solving my problem using this solution but I'm still having some issue. Could you perhaps provide insight? The question can be found here: stackoverflow.com/questions/28704644/…

                                – jasenmp
                                Feb 25 '15 at 0:15
















                              This is very helpful, I feel like I'm on the cusp of solving my problem using this solution but I'm still having some issue. Could you perhaps provide insight? The question can be found here: stackoverflow.com/questions/28704644/…

                              – jasenmp
                              Feb 25 '15 at 0:15





                              This is very helpful, I feel like I'm on the cusp of solving my problem using this solution but I'm still having some issue. Could you perhaps provide insight? The question can be found here: stackoverflow.com/questions/28704644/…

                              – jasenmp
                              Feb 25 '15 at 0:15











                              15














                              I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.



                              Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.



                              Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.



                               /**
                              * @param array multidimensional
                              * @param string value to search for, ie a specific field name like name_first
                              * @param string associative key to find it in, ie field_name
                              *
                              * @return array keys.
                              */
                              function search_revisions($dataArray, $search_value, $key_to_search)
                              // This function will search the revisions for a certain value
                              // related to the associative key you are looking for.
                              $keys = array();
                              foreach ($dataArray as $key => $cur_value)
                              if ($cur_value[$key_to_search] == $search_value)
                              $keys = $key;


                              return $keys;



                              Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.



                              This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).



                              /**
                              * @param array multidimensional
                              * @param string $search_value The value to search for, ie a specific 'Taylor'
                              * @param string $key_to_search The associative key to find it in, ie first_name
                              * @param string $other_matching_key The associative key to find in the matches for employed
                              * @param string $other_matching_value The value to find in that matching associative key, ie true
                              *
                              * @return array keys, ie all the people with the first name 'Taylor' that are employed.
                              */
                              function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null)
                              // This function will search the revisions for a certain value
                              // related to the associative key you are looking for.
                              $keys = array();
                              foreach ($dataArray as $key => $cur_value)
                              if ($cur_value[$key_to_search] == $search_value)
                              if (isset($other_matching_key) && isset($other_matching_value))
                              if ($cur_value[$other_matching_key] == $other_matching_value)
                              $keys = $key;

                              else
                              // I must keep in mind that some searches may have multiple
                              // matches and others would not, so leave it open with no continues.
                              $keys = $key;



                              return $keys;



                              Use of function



                              $data = array(
                              array(
                              'cust_group' => 6,
                              'price' => 13.21,
                              'price_qty' => 5
                              ),
                              array(
                              'cust_group' => 8,
                              'price' => 15.25,
                              'price_qty' => 4
                              ),
                              array(
                              'cust_group' => 8,
                              'price' => 12.75,
                              'price_qty' => 10
                              )
                              );

                              $findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
                              print_r($findKey);


                              Result



                              Array ( [0] => 2 ) 





                              share|improve this answer





























                                15














                                I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.



                                Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.



                                Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.



                                 /**
                                * @param array multidimensional
                                * @param string value to search for, ie a specific field name like name_first
                                * @param string associative key to find it in, ie field_name
                                *
                                * @return array keys.
                                */
                                function search_revisions($dataArray, $search_value, $key_to_search)
                                // This function will search the revisions for a certain value
                                // related to the associative key you are looking for.
                                $keys = array();
                                foreach ($dataArray as $key => $cur_value)
                                if ($cur_value[$key_to_search] == $search_value)
                                $keys = $key;


                                return $keys;



                                Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.



                                This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).



                                /**
                                * @param array multidimensional
                                * @param string $search_value The value to search for, ie a specific 'Taylor'
                                * @param string $key_to_search The associative key to find it in, ie first_name
                                * @param string $other_matching_key The associative key to find in the matches for employed
                                * @param string $other_matching_value The value to find in that matching associative key, ie true
                                *
                                * @return array keys, ie all the people with the first name 'Taylor' that are employed.
                                */
                                function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null)
                                // This function will search the revisions for a certain value
                                // related to the associative key you are looking for.
                                $keys = array();
                                foreach ($dataArray as $key => $cur_value)
                                if ($cur_value[$key_to_search] == $search_value)
                                if (isset($other_matching_key) && isset($other_matching_value))
                                if ($cur_value[$other_matching_key] == $other_matching_value)
                                $keys = $key;

                                else
                                // I must keep in mind that some searches may have multiple
                                // matches and others would not, so leave it open with no continues.
                                $keys = $key;



                                return $keys;



                                Use of function



                                $data = array(
                                array(
                                'cust_group' => 6,
                                'price' => 13.21,
                                'price_qty' => 5
                                ),
                                array(
                                'cust_group' => 8,
                                'price' => 15.25,
                                'price_qty' => 4
                                ),
                                array(
                                'cust_group' => 8,
                                'price' => 12.75,
                                'price_qty' => 10
                                )
                                );

                                $findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
                                print_r($findKey);


                                Result



                                Array ( [0] => 2 ) 





                                share|improve this answer



























                                  15












                                  15








                                  15







                                  I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.



                                  Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.



                                  Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.



                                   /**
                                  * @param array multidimensional
                                  * @param string value to search for, ie a specific field name like name_first
                                  * @param string associative key to find it in, ie field_name
                                  *
                                  * @return array keys.
                                  */
                                  function search_revisions($dataArray, $search_value, $key_to_search)
                                  // This function will search the revisions for a certain value
                                  // related to the associative key you are looking for.
                                  $keys = array();
                                  foreach ($dataArray as $key => $cur_value)
                                  if ($cur_value[$key_to_search] == $search_value)
                                  $keys = $key;


                                  return $keys;



                                  Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.



                                  This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).



                                  /**
                                  * @param array multidimensional
                                  * @param string $search_value The value to search for, ie a specific 'Taylor'
                                  * @param string $key_to_search The associative key to find it in, ie first_name
                                  * @param string $other_matching_key The associative key to find in the matches for employed
                                  * @param string $other_matching_value The value to find in that matching associative key, ie true
                                  *
                                  * @return array keys, ie all the people with the first name 'Taylor' that are employed.
                                  */
                                  function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null)
                                  // This function will search the revisions for a certain value
                                  // related to the associative key you are looking for.
                                  $keys = array();
                                  foreach ($dataArray as $key => $cur_value)
                                  if ($cur_value[$key_to_search] == $search_value)
                                  if (isset($other_matching_key) && isset($other_matching_value))
                                  if ($cur_value[$other_matching_key] == $other_matching_value)
                                  $keys = $key;

                                  else
                                  // I must keep in mind that some searches may have multiple
                                  // matches and others would not, so leave it open with no continues.
                                  $keys = $key;



                                  return $keys;



                                  Use of function



                                  $data = array(
                                  array(
                                  'cust_group' => 6,
                                  'price' => 13.21,
                                  'price_qty' => 5
                                  ),
                                  array(
                                  'cust_group' => 8,
                                  'price' => 15.25,
                                  'price_qty' => 4
                                  ),
                                  array(
                                  'cust_group' => 8,
                                  'price' => 12.75,
                                  'price_qty' => 10
                                  )
                                  );

                                  $findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
                                  print_r($findKey);


                                  Result



                                  Array ( [0] => 2 ) 





                                  share|improve this answer















                                  I know this was already answered, but I used this and extended it a little more in my code so that you didn't have search by only the uid. I just want to share it for anyone else who may need that functionality.



                                  Here's my example and please bare in mind this is my first answer. I took out the param array because I only needed to search one specific array, but you could easily add it in. I wanted to essentially search by more than just the uid.



                                  Also, in my situation there may be multiple keys to return as a result of searching by other fields that may not be unique.



                                   /**
                                  * @param array multidimensional
                                  * @param string value to search for, ie a specific field name like name_first
                                  * @param string associative key to find it in, ie field_name
                                  *
                                  * @return array keys.
                                  */
                                  function search_revisions($dataArray, $search_value, $key_to_search)
                                  // This function will search the revisions for a certain value
                                  // related to the associative key you are looking for.
                                  $keys = array();
                                  foreach ($dataArray as $key => $cur_value)
                                  if ($cur_value[$key_to_search] == $search_value)
                                  $keys = $key;


                                  return $keys;



                                  Later, I ended up writing this to allow me to search for another value and associative key. So my first example allows you to search for a value in any specific associative key, and return all the matches.



                                  This second example shows you where a value ('Taylor') is found in a certain associative key (first_name) AND another value (true) is found in another associative key (employed), and returns all matches (Keys where people with first name 'Taylor' AND are employed).



                                  /**
                                  * @param array multidimensional
                                  * @param string $search_value The value to search for, ie a specific 'Taylor'
                                  * @param string $key_to_search The associative key to find it in, ie first_name
                                  * @param string $other_matching_key The associative key to find in the matches for employed
                                  * @param string $other_matching_value The value to find in that matching associative key, ie true
                                  *
                                  * @return array keys, ie all the people with the first name 'Taylor' that are employed.
                                  */
                                  function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null)
                                  // This function will search the revisions for a certain value
                                  // related to the associative key you are looking for.
                                  $keys = array();
                                  foreach ($dataArray as $key => $cur_value)
                                  if ($cur_value[$key_to_search] == $search_value)
                                  if (isset($other_matching_key) && isset($other_matching_value))
                                  if ($cur_value[$other_matching_key] == $other_matching_value)
                                  $keys = $key;

                                  else
                                  // I must keep in mind that some searches may have multiple
                                  // matches and others would not, so leave it open with no continues.
                                  $keys = $key;



                                  return $keys;



                                  Use of function



                                  $data = array(
                                  array(
                                  'cust_group' => 6,
                                  'price' => 13.21,
                                  'price_qty' => 5
                                  ),
                                  array(
                                  'cust_group' => 8,
                                  'price' => 15.25,
                                  'price_qty' => 4
                                  ),
                                  array(
                                  'cust_group' => 8,
                                  'price' => 12.75,
                                  'price_qty' => 10
                                  )
                                  );

                                  $findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
                                  print_r($findKey);


                                  Result



                                  Array ( [0] => 2 ) 






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Feb 23 '18 at 14:09









                                  Nadeem0035

                                  1,4051222




                                  1,4051222










                                  answered Feb 22 '13 at 19:29









                                  amurrellamurrell

                                  1,2981321




                                  1,2981321





















                                      8














                                      I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:



                                       $arr = array(
                                      'XXX'=>array(
                                      'YYY'=> array(
                                      'AAA'=> array(
                                      'keyN' =>'value1'
                                      )
                                      ),
                                      'ZZZ'=> array(
                                      'BBB'=> array(
                                      'keyN' => 'value2'
                                      )
                                      )
                                      //.....
                                      )
                                      );


                                      $result = searchItemsByKey($arr,'keyN');

                                      print '<pre>';
                                      print_r($result);
                                      print '<pre>';
                                      // OUTPUT
                                      Array
                                      (
                                      [0] => value1
                                      [1] => value2
                                      )


                                      Function code:



                                      function searchItemsByKey($array, $key)

                                      $results = array();

                                      if (is_array($array))

                                      if (isset($array[$key]) && key($array)==$key)
                                      $results = $array[$key];

                                      foreach ($array as $sub_array)
                                      $results = array_merge($results, searchItemsByKey($sub_array, $key));


                                      return $results;






                                      share|improve this answer





























                                        8














                                        I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:



                                         $arr = array(
                                        'XXX'=>array(
                                        'YYY'=> array(
                                        'AAA'=> array(
                                        'keyN' =>'value1'
                                        )
                                        ),
                                        'ZZZ'=> array(
                                        'BBB'=> array(
                                        'keyN' => 'value2'
                                        )
                                        )
                                        //.....
                                        )
                                        );


                                        $result = searchItemsByKey($arr,'keyN');

                                        print '<pre>';
                                        print_r($result);
                                        print '<pre>';
                                        // OUTPUT
                                        Array
                                        (
                                        [0] => value1
                                        [1] => value2
                                        )


                                        Function code:



                                        function searchItemsByKey($array, $key)

                                        $results = array();

                                        if (is_array($array))

                                        if (isset($array[$key]) && key($array)==$key)
                                        $results = $array[$key];

                                        foreach ($array as $sub_array)
                                        $results = array_merge($results, searchItemsByKey($sub_array, $key));


                                        return $results;






                                        share|improve this answer



























                                          8












                                          8








                                          8







                                          I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:



                                           $arr = array(
                                          'XXX'=>array(
                                          'YYY'=> array(
                                          'AAA'=> array(
                                          'keyN' =>'value1'
                                          )
                                          ),
                                          'ZZZ'=> array(
                                          'BBB'=> array(
                                          'keyN' => 'value2'
                                          )
                                          )
                                          //.....
                                          )
                                          );


                                          $result = searchItemsByKey($arr,'keyN');

                                          print '<pre>';
                                          print_r($result);
                                          print '<pre>';
                                          // OUTPUT
                                          Array
                                          (
                                          [0] => value1
                                          [1] => value2
                                          )


                                          Function code:



                                          function searchItemsByKey($array, $key)

                                          $results = array();

                                          if (is_array($array))

                                          if (isset($array[$key]) && key($array)==$key)
                                          $results = $array[$key];

                                          foreach ($array as $sub_array)
                                          $results = array_merge($results, searchItemsByKey($sub_array, $key));


                                          return $results;






                                          share|improve this answer















                                          I modified one of examples below description function array_search. Function searchItemsByKey return all value(s) by $key from multidimensional array ( N levels). Perhaps , it would be useful for somebody. Example:



                                           $arr = array(
                                          'XXX'=>array(
                                          'YYY'=> array(
                                          'AAA'=> array(
                                          'keyN' =>'value1'
                                          )
                                          ),
                                          'ZZZ'=> array(
                                          'BBB'=> array(
                                          'keyN' => 'value2'
                                          )
                                          )
                                          //.....
                                          )
                                          );


                                          $result = searchItemsByKey($arr,'keyN');

                                          print '<pre>';
                                          print_r($result);
                                          print '<pre>';
                                          // OUTPUT
                                          Array
                                          (
                                          [0] => value1
                                          [1] => value2
                                          )


                                          Function code:



                                          function searchItemsByKey($array, $key)

                                          $results = array();

                                          if (is_array($array))

                                          if (isset($array[$key]) && key($array)==$key)
                                          $results = $array[$key];

                                          foreach ($array as $sub_array)
                                          $results = array_merge($results, searchItemsByKey($sub_array, $key));


                                          return $results;







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Sep 16 '14 at 6:15

























                                          answered Jan 25 '14 at 14:02









                                          voodoo417voodoo417

                                          9,23032229




                                          9,23032229





















                                              7














                                              In later versions of PHP (>= 5.5.0) you can use this one-liner:



                                              $key = array_search('100', array_column($userdb, 'uid'));





                                              share|improve this answer





























                                                7














                                                In later versions of PHP (>= 5.5.0) you can use this one-liner:



                                                $key = array_search('100', array_column($userdb, 'uid'));





                                                share|improve this answer



























                                                  7












                                                  7








                                                  7







                                                  In later versions of PHP (>= 5.5.0) you can use this one-liner:



                                                  $key = array_search('100', array_column($userdb, 'uid'));





                                                  share|improve this answer















                                                  In later versions of PHP (>= 5.5.0) you can use this one-liner:



                                                  $key = array_search('100', array_column($userdb, 'uid'));






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Apr 10 '18 at 11:25









                                                  Stephen Kennedy

                                                  7,199134967




                                                  7,199134967










                                                  answered Jun 14 '17 at 8:59









                                                  Iryna BatvinaIryna Batvina

                                                  43753




                                                  43753





















                                                      4














                                                      Looks array_filter will be suitable solution for this...



                                                      $userdb=Array
                                                      (
                                                      (0) => Array
                                                      (
                                                      (uid) => '100',
                                                      (name) => 'Sandra Shush',
                                                      (url) => 'urlof100'
                                                      ),

                                                      (1) => Array
                                                      (
                                                      (uid) => '5465',
                                                      (name) => 'Stefanie Mcmohn',
                                                      (pic_square) => 'urlof100'
                                                      ),

                                                      (2) => Array
                                                      (
                                                      (uid) => '40489',
                                                      (name) => 'Michael',
                                                      (pic_square) => 'urlof40489'
                                                      )
                                                      );


                                                      PHP Code



                                                      <?php 
                                                      $search = 5465;
                                                      $found = array_filter($userdb,function($v,$k) use ($search)
                                                      return $v['uid'] => $search;
                                                      )

                                                      $values= print_r(array_value($found));
                                                      $keys = print_r(array_keys($found));





                                                      share|improve this answer

























                                                      • @BEJAM SHIVA PRASAD could you please help me out with this stackoverflow.com/questions/44721195/… ?

                                                        – Valay
                                                        Jun 23 '17 at 13:38











                                                      • shows an error :syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ';'

                                                        – Shihas
                                                        Apr 11 '18 at 11:21












                                                      • Can you please paste more info I mean which line and your code and array structure.

                                                        – BEJGAM SHIVA PRASAD
                                                        Apr 12 '18 at 4:01















                                                      4














                                                      Looks array_filter will be suitable solution for this...



                                                      $userdb=Array
                                                      (
                                                      (0) => Array
                                                      (
                                                      (uid) => '100',
                                                      (name) => 'Sandra Shush',
                                                      (url) => 'urlof100'
                                                      ),

                                                      (1) => Array
                                                      (
                                                      (uid) => '5465',
                                                      (name) => 'Stefanie Mcmohn',
                                                      (pic_square) => 'urlof100'
                                                      ),

                                                      (2) => Array
                                                      (
                                                      (uid) => '40489',
                                                      (name) => 'Michael',
                                                      (pic_square) => 'urlof40489'
                                                      )
                                                      );


                                                      PHP Code



                                                      <?php 
                                                      $search = 5465;
                                                      $found = array_filter($userdb,function($v,$k) use ($search)
                                                      return $v['uid'] => $search;
                                                      )

                                                      $values= print_r(array_value($found));
                                                      $keys = print_r(array_keys($found));





                                                      share|improve this answer

























                                                      • @BEJAM SHIVA PRASAD could you please help me out with this stackoverflow.com/questions/44721195/… ?

                                                        – Valay
                                                        Jun 23 '17 at 13:38











                                                      • shows an error :syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ';'

                                                        – Shihas
                                                        Apr 11 '18 at 11:21












                                                      • Can you please paste more info I mean which line and your code and array structure.

                                                        – BEJGAM SHIVA PRASAD
                                                        Apr 12 '18 at 4:01













                                                      4












                                                      4








                                                      4







                                                      Looks array_filter will be suitable solution for this...



                                                      $userdb=Array
                                                      (
                                                      (0) => Array
                                                      (
                                                      (uid) => '100',
                                                      (name) => 'Sandra Shush',
                                                      (url) => 'urlof100'
                                                      ),

                                                      (1) => Array
                                                      (
                                                      (uid) => '5465',
                                                      (name) => 'Stefanie Mcmohn',
                                                      (pic_square) => 'urlof100'
                                                      ),

                                                      (2) => Array
                                                      (
                                                      (uid) => '40489',
                                                      (name) => 'Michael',
                                                      (pic_square) => 'urlof40489'
                                                      )
                                                      );


                                                      PHP Code



                                                      <?php 
                                                      $search = 5465;
                                                      $found = array_filter($userdb,function($v,$k) use ($search)
                                                      return $v['uid'] => $search;
                                                      )

                                                      $values= print_r(array_value($found));
                                                      $keys = print_r(array_keys($found));





                                                      share|improve this answer















                                                      Looks array_filter will be suitable solution for this...



                                                      $userdb=Array
                                                      (
                                                      (0) => Array
                                                      (
                                                      (uid) => '100',
                                                      (name) => 'Sandra Shush',
                                                      (url) => 'urlof100'
                                                      ),

                                                      (1) => Array
                                                      (
                                                      (uid) => '5465',
                                                      (name) => 'Stefanie Mcmohn',
                                                      (pic_square) => 'urlof100'
                                                      ),

                                                      (2) => Array
                                                      (
                                                      (uid) => '40489',
                                                      (name) => 'Michael',
                                                      (pic_square) => 'urlof40489'
                                                      )
                                                      );


                                                      PHP Code



                                                      <?php 
                                                      $search = 5465;
                                                      $found = array_filter($userdb,function($v,$k) use ($search)
                                                      return $v['uid'] => $search;
                                                      )

                                                      $values= print_r(array_value($found));
                                                      $keys = print_r(array_keys($found));






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Jan 2 '17 at 6:49

























                                                      answered Dec 16 '16 at 15:01









                                                      BEJGAM SHIVA PRASADBEJGAM SHIVA PRASAD

                                                      768617




                                                      768617












                                                      • @BEJAM SHIVA PRASAD could you please help me out with this stackoverflow.com/questions/44721195/… ?

                                                        – Valay
                                                        Jun 23 '17 at 13:38











                                                      • shows an error :syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ';'

                                                        – Shihas
                                                        Apr 11 '18 at 11:21












                                                      • Can you please paste more info I mean which line and your code and array structure.

                                                        – BEJGAM SHIVA PRASAD
                                                        Apr 12 '18 at 4:01

















                                                      • @BEJAM SHIVA PRASAD could you please help me out with this stackoverflow.com/questions/44721195/… ?

                                                        – Valay
                                                        Jun 23 '17 at 13:38











                                                      • shows an error :syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ';'

                                                        – Shihas
                                                        Apr 11 '18 at 11:21












                                                      • Can you please paste more info I mean which line and your code and array structure.

                                                        – BEJGAM SHIVA PRASAD
                                                        Apr 12 '18 at 4:01
















                                                      @BEJAM SHIVA PRASAD could you please help me out with this stackoverflow.com/questions/44721195/… ?

                                                      – Valay
                                                      Jun 23 '17 at 13:38





                                                      @BEJAM SHIVA PRASAD could you please help me out with this stackoverflow.com/questions/44721195/… ?

                                                      – Valay
                                                      Jun 23 '17 at 13:38













                                                      shows an error :syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ';'

                                                      – Shihas
                                                      Apr 11 '18 at 11:21






                                                      shows an error :syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ';'

                                                      – Shihas
                                                      Apr 11 '18 at 11:21














                                                      Can you please paste more info I mean which line and your code and array structure.

                                                      – BEJGAM SHIVA PRASAD
                                                      Apr 12 '18 at 4:01





                                                      Can you please paste more info I mean which line and your code and array structure.

                                                      – BEJGAM SHIVA PRASAD
                                                      Apr 12 '18 at 4:01











                                                      3














                                                      Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.



                                                      function searchArrayKeyVal($sKey, $id, $array) 
                                                      foreach ($array as $key => $val)
                                                      if ($val[$sKey] == $id)
                                                      return $key;


                                                      return false;



                                                      Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.



                                                       // Array Data Of Users
                                                      $userdb = array (
                                                      array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
                                                      array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
                                                      array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
                                                      );

                                                      // Obtain The Key Of The Array
                                                      $arrayKey = searchArrayKeyVal("uid", '100', $userdb);
                                                      if ($arrayKey!==false)
                                                      echo "Search Result: ", $userdb[$arrayKey]['name'];
                                                      else
                                                      echo "Search Result can not be found";



                                                      PHP Fiddle Example






                                                      share|improve this answer

























                                                      • Another reason i use SOF... easier to google and find my own code or something i remember.. +1 for my own public repository

                                                        – Mayhem
                                                        Feb 18 '15 at 23:38











                                                      • BTW, you are setting the result to null and then in the code, you are comparing it to false.

                                                        – Taha Paksu
                                                        Jun 20 '16 at 21:16











                                                      • Corrected with returning false instead, but null might be better incase of checking for booleans

                                                        – Mayhem
                                                        Jun 21 '16 at 0:46















                                                      3














                                                      Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.



                                                      function searchArrayKeyVal($sKey, $id, $array) 
                                                      foreach ($array as $key => $val)
                                                      if ($val[$sKey] == $id)
                                                      return $key;


                                                      return false;



                                                      Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.



                                                       // Array Data Of Users
                                                      $userdb = array (
                                                      array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
                                                      array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
                                                      array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
                                                      );

                                                      // Obtain The Key Of The Array
                                                      $arrayKey = searchArrayKeyVal("uid", '100', $userdb);
                                                      if ($arrayKey!==false)
                                                      echo "Search Result: ", $userdb[$arrayKey]['name'];
                                                      else
                                                      echo "Search Result can not be found";



                                                      PHP Fiddle Example






                                                      share|improve this answer

























                                                      • Another reason i use SOF... easier to google and find my own code or something i remember.. +1 for my own public repository

                                                        – Mayhem
                                                        Feb 18 '15 at 23:38











                                                      • BTW, you are setting the result to null and then in the code, you are comparing it to false.

                                                        – Taha Paksu
                                                        Jun 20 '16 at 21:16











                                                      • Corrected with returning false instead, but null might be better incase of checking for booleans

                                                        – Mayhem
                                                        Jun 21 '16 at 0:46













                                                      3












                                                      3








                                                      3







                                                      Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.



                                                      function searchArrayKeyVal($sKey, $id, $array) 
                                                      foreach ($array as $key => $val)
                                                      if ($val[$sKey] == $id)
                                                      return $key;


                                                      return false;



                                                      Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.



                                                       // Array Data Of Users
                                                      $userdb = array (
                                                      array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
                                                      array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
                                                      array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
                                                      );

                                                      // Obtain The Key Of The Array
                                                      $arrayKey = searchArrayKeyVal("uid", '100', $userdb);
                                                      if ($arrayKey!==false)
                                                      echo "Search Result: ", $userdb[$arrayKey]['name'];
                                                      else
                                                      echo "Search Result can not be found";



                                                      PHP Fiddle Example






                                                      share|improve this answer















                                                      Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.



                                                      function searchArrayKeyVal($sKey, $id, $array) 
                                                      foreach ($array as $key => $val)
                                                      if ($val[$sKey] == $id)
                                                      return $key;


                                                      return false;



                                                      Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.



                                                       // Array Data Of Users
                                                      $userdb = array (
                                                      array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
                                                      array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
                                                      array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
                                                      );

                                                      // Obtain The Key Of The Array
                                                      $arrayKey = searchArrayKeyVal("uid", '100', $userdb);
                                                      if ($arrayKey!==false)
                                                      echo "Search Result: ", $userdb[$arrayKey]['name'];
                                                      else
                                                      echo "Search Result can not be found";



                                                      PHP Fiddle Example







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Jun 21 '16 at 0:46

























                                                      answered Feb 4 '15 at 2:02









                                                      MayhemMayhem

                                                      2,21911418




                                                      2,21911418












                                                      • Another reason i use SOF... easier to google and find my own code or something i remember.. +1 for my own public repository

                                                        – Mayhem
                                                        Feb 18 '15 at 23:38











                                                      • BTW, you are setting the result to null and then in the code, you are comparing it to false.

                                                        – Taha Paksu
                                                        Jun 20 '16 at 21:16











                                                      • Corrected with returning false instead, but null might be better incase of checking for booleans

                                                        – Mayhem
                                                        Jun 21 '16 at 0:46

















                                                      • Another reason i use SOF... easier to google and find my own code or something i remember.. +1 for my own public repository

                                                        – Mayhem
                                                        Feb 18 '15 at 23:38











                                                      • BTW, you are setting the result to null and then in the code, you are comparing it to false.

                                                        – Taha Paksu
                                                        Jun 20 '16 at 21:16











                                                      • Corrected with returning false instead, but null might be better incase of checking for booleans

                                                        – Mayhem
                                                        Jun 21 '16 at 0:46
















                                                      Another reason i use SOF... easier to google and find my own code or something i remember.. +1 for my own public repository

                                                      – Mayhem
                                                      Feb 18 '15 at 23:38





                                                      Another reason i use SOF... easier to google and find my own code or something i remember.. +1 for my own public repository

                                                      – Mayhem
                                                      Feb 18 '15 at 23:38













                                                      BTW, you are setting the result to null and then in the code, you are comparing it to false.

                                                      – Taha Paksu
                                                      Jun 20 '16 at 21:16





                                                      BTW, you are setting the result to null and then in the code, you are comparing it to false.

                                                      – Taha Paksu
                                                      Jun 20 '16 at 21:16













                                                      Corrected with returning false instead, but null might be better incase of checking for booleans

                                                      – Mayhem
                                                      Jun 21 '16 at 0:46





                                                      Corrected with returning false instead, but null might be better incase of checking for booleans

                                                      – Mayhem
                                                      Jun 21 '16 at 0:46











                                                      2














                                                      Here is one liner for the same,



                                                      $pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];





                                                      share|improve this answer























                                                      • Thanks.. This is what I exactly need.

                                                        – Dolly
                                                        May 3 '18 at 9:35











                                                      • welcome mate!!!

                                                        – Rahul Meshram
                                                        May 7 '18 at 8:55















                                                      2














                                                      Here is one liner for the same,



                                                      $pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];





                                                      share|improve this answer























                                                      • Thanks.. This is what I exactly need.

                                                        – Dolly
                                                        May 3 '18 at 9:35











                                                      • welcome mate!!!

                                                        – Rahul Meshram
                                                        May 7 '18 at 8:55













                                                      2












                                                      2








                                                      2







                                                      Here is one liner for the same,



                                                      $pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];





                                                      share|improve this answer













                                                      Here is one liner for the same,



                                                      $pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];






                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Dec 22 '17 at 9:54









                                                      Rahul MeshramRahul Meshram

                                                      6,52441839




                                                      6,52441839












                                                      • Thanks.. This is what I exactly need.

                                                        – Dolly
                                                        May 3 '18 at 9:35











                                                      • welcome mate!!!

                                                        – Rahul Meshram
                                                        May 7 '18 at 8:55

















                                                      • Thanks.. This is what I exactly need.

                                                        – Dolly
                                                        May 3 '18 at 9:35











                                                      • welcome mate!!!

                                                        – Rahul Meshram
                                                        May 7 '18 at 8:55
















                                                      Thanks.. This is what I exactly need.

                                                      – Dolly
                                                      May 3 '18 at 9:35





                                                      Thanks.. This is what I exactly need.

                                                      – Dolly
                                                      May 3 '18 at 9:35













                                                      welcome mate!!!

                                                      – Rahul Meshram
                                                      May 7 '18 at 8:55





                                                      welcome mate!!!

                                                      – Rahul Meshram
                                                      May 7 '18 at 8:55











                                                      1














                                                      I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:



                                                      function search_in_array_r($needle, $array) 
                                                      $found = array();
                                                      foreach ($array as $key => $val)
                                                      if ($val[1] == $needle)
                                                      array_push($found, $val[1]);


                                                      if (count($found) != 0)
                                                      return $found;
                                                      else
                                                      return null;






                                                      share|improve this answer





























                                                        1














                                                        I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:



                                                        function search_in_array_r($needle, $array) 
                                                        $found = array();
                                                        foreach ($array as $key => $val)
                                                        if ($val[1] == $needle)
                                                        array_push($found, $val[1]);


                                                        if (count($found) != 0)
                                                        return $found;
                                                        else
                                                        return null;






                                                        share|improve this answer



























                                                          1












                                                          1








                                                          1







                                                          I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:



                                                          function search_in_array_r($needle, $array) 
                                                          $found = array();
                                                          foreach ($array as $key => $val)
                                                          if ($val[1] == $needle)
                                                          array_push($found, $val[1]);


                                                          if (count($found) != 0)
                                                          return $found;
                                                          else
                                                          return null;






                                                          share|improve this answer















                                                          I had to use un function which finds every elements in an array. So I modified the function done by Jakub Truneček as follow:



                                                          function search_in_array_r($needle, $array) 
                                                          $found = array();
                                                          foreach ($array as $key => $val)
                                                          if ($val[1] == $needle)
                                                          array_push($found, $val[1]);


                                                          if (count($found) != 0)
                                                          return $found;
                                                          else
                                                          return null;







                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Sep 17 '13 at 12:58

























                                                          answered Sep 17 '13 at 12:42









                                                          csi_berncsi_bern

                                                          135




                                                          135





















                                                              1














                                                              /**
                                                              * searches a simple as well as multi dimension array
                                                              * @param type $needle
                                                              * @param type $haystack
                                                              * @return boolean
                                                              */
                                                              public static function in_array_multi($needle, $haystack)
                                                              $needle = trim($needle);
                                                              if(!is_array($haystack))
                                                              return False;

                                                              foreach($haystack as $key=>$value)
                                                              if(is_array($value))
                                                              if(self::in_array_multi($needle, $value))
                                                              return True;
                                                              else
                                                              self::in_array_multi($needle, $value);

                                                              else
                                                              if(trim($value) === trim($needle))//visibility fix//
                                                              error_log("$value === $needle setting visibility to 1 hidden");
                                                              return True;



                                                              return False;






                                                              share|improve this answer





























                                                                1














                                                                /**
                                                                * searches a simple as well as multi dimension array
                                                                * @param type $needle
                                                                * @param type $haystack
                                                                * @return boolean
                                                                */
                                                                public static function in_array_multi($needle, $haystack)
                                                                $needle = trim($needle);
                                                                if(!is_array($haystack))
                                                                return False;

                                                                foreach($haystack as $key=>$value)
                                                                if(is_array($value))
                                                                if(self::in_array_multi($needle, $value))
                                                                return True;
                                                                else
                                                                self::in_array_multi($needle, $value);

                                                                else
                                                                if(trim($value) === trim($needle))//visibility fix//
                                                                error_log("$value === $needle setting visibility to 1 hidden");
                                                                return True;



                                                                return False;






                                                                share|improve this answer



























                                                                  1












                                                                  1








                                                                  1







                                                                  /**
                                                                  * searches a simple as well as multi dimension array
                                                                  * @param type $needle
                                                                  * @param type $haystack
                                                                  * @return boolean
                                                                  */
                                                                  public static function in_array_multi($needle, $haystack)
                                                                  $needle = trim($needle);
                                                                  if(!is_array($haystack))
                                                                  return False;

                                                                  foreach($haystack as $key=>$value)
                                                                  if(is_array($value))
                                                                  if(self::in_array_multi($needle, $value))
                                                                  return True;
                                                                  else
                                                                  self::in_array_multi($needle, $value);

                                                                  else
                                                                  if(trim($value) === trim($needle))//visibility fix//
                                                                  error_log("$value === $needle setting visibility to 1 hidden");
                                                                  return True;



                                                                  return False;






                                                                  share|improve this answer















                                                                  /**
                                                                  * searches a simple as well as multi dimension array
                                                                  * @param type $needle
                                                                  * @param type $haystack
                                                                  * @return boolean
                                                                  */
                                                                  public static function in_array_multi($needle, $haystack)
                                                                  $needle = trim($needle);
                                                                  if(!is_array($haystack))
                                                                  return False;

                                                                  foreach($haystack as $key=>$value)
                                                                  if(is_array($value))
                                                                  if(self::in_array_multi($needle, $value))
                                                                  return True;
                                                                  else
                                                                  self::in_array_multi($needle, $value);

                                                                  else
                                                                  if(trim($value) === trim($needle))//visibility fix//
                                                                  error_log("$value === $needle setting visibility to 1 hidden");
                                                                  return True;



                                                                  return False;







                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Jul 28 '14 at 4:52

























                                                                  answered Jul 28 '14 at 4:47









                                                                  Ahad AliAhad Ali

                                                                  36539




                                                                  36539





















                                                                      1














                                                                      you can use this function ;
                                                                      https://github.com/serhatozles/ArrayAdvancedSearch



                                                                      <?php 
                                                                      include('ArraySearch.php');

                                                                      $query = "a='Example World' and b>='2'";

                                                                      $Array = array(
                                                                      'a' => array('d' => '2'),
                                                                      array('a' => 'Example World','b' => '2'),
                                                                      array('c' => '3'), array('d' => '4'),
                                                                      );

                                                                      $Result = ArraySearch($Array,$query,1);

                                                                      echo '<pre>';
                                                                      print_r($Result);
                                                                      echo '</pre>';

                                                                      // Output:
                                                                      // Array
                                                                      // (
                                                                      // [0] => Array
                                                                      // (
                                                                      // [a] => Example World
                                                                      // [b] => 2
                                                                      // )
                                                                      //
                                                                      // )





                                                                      share|improve this answer





























                                                                        1














                                                                        you can use this function ;
                                                                        https://github.com/serhatozles/ArrayAdvancedSearch



                                                                        <?php 
                                                                        include('ArraySearch.php');

                                                                        $query = "a='Example World' and b>='2'";

                                                                        $Array = array(
                                                                        'a' => array('d' => '2'),
                                                                        array('a' => 'Example World','b' => '2'),
                                                                        array('c' => '3'), array('d' => '4'),
                                                                        );

                                                                        $Result = ArraySearch($Array,$query,1);

                                                                        echo '<pre>';
                                                                        print_r($Result);
                                                                        echo '</pre>';

                                                                        // Output:
                                                                        // Array
                                                                        // (
                                                                        // [0] => Array
                                                                        // (
                                                                        // [a] => Example World
                                                                        // [b] => 2
                                                                        // )
                                                                        //
                                                                        // )





                                                                        share|improve this answer



























                                                                          1












                                                                          1








                                                                          1







                                                                          you can use this function ;
                                                                          https://github.com/serhatozles/ArrayAdvancedSearch



                                                                          <?php 
                                                                          include('ArraySearch.php');

                                                                          $query = "a='Example World' and b>='2'";

                                                                          $Array = array(
                                                                          'a' => array('d' => '2'),
                                                                          array('a' => 'Example World','b' => '2'),
                                                                          array('c' => '3'), array('d' => '4'),
                                                                          );

                                                                          $Result = ArraySearch($Array,$query,1);

                                                                          echo '<pre>';
                                                                          print_r($Result);
                                                                          echo '</pre>';

                                                                          // Output:
                                                                          // Array
                                                                          // (
                                                                          // [0] => Array
                                                                          // (
                                                                          // [a] => Example World
                                                                          // [b] => 2
                                                                          // )
                                                                          //
                                                                          // )





                                                                          share|improve this answer















                                                                          you can use this function ;
                                                                          https://github.com/serhatozles/ArrayAdvancedSearch



                                                                          <?php 
                                                                          include('ArraySearch.php');

                                                                          $query = "a='Example World' and b>='2'";

                                                                          $Array = array(
                                                                          'a' => array('d' => '2'),
                                                                          array('a' => 'Example World','b' => '2'),
                                                                          array('c' => '3'), array('d' => '4'),
                                                                          );

                                                                          $Result = ArraySearch($Array,$query,1);

                                                                          echo '<pre>';
                                                                          print_r($Result);
                                                                          echo '</pre>';

                                                                          // Output:
                                                                          // Array
                                                                          // (
                                                                          // [0] => Array
                                                                          // (
                                                                          // [a] => Example World
                                                                          // [b] => 2
                                                                          // )
                                                                          //
                                                                          // )






                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Jan 11 '15 at 15:09

























                                                                          answered Jan 31 '14 at 7:56









                                                                          SerhatSerhat

                                                                          166312




                                                                          166312





















                                                                              1














                                                                              $a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

                                                                              $found = null;
                                                                              $search = 'eee';

                                                                              array_walk($a, function ($k, $v) use ($search, &$found)
                                                                              if (in_array($search, $k))
                                                                              $found = $v;

                                                                              );

                                                                              var_dump($found);





                                                                              share|improve this answer



























                                                                                1














                                                                                $a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

                                                                                $found = null;
                                                                                $search = 'eee';

                                                                                array_walk($a, function ($k, $v) use ($search, &$found)
                                                                                if (in_array($search, $k))
                                                                                $found = $v;

                                                                                );

                                                                                var_dump($found);





                                                                                share|improve this answer

























                                                                                  1












                                                                                  1








                                                                                  1







                                                                                  $a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

                                                                                  $found = null;
                                                                                  $search = 'eee';

                                                                                  array_walk($a, function ($k, $v) use ($search, &$found)
                                                                                  if (in_array($search, $k))
                                                                                  $found = $v;

                                                                                  );

                                                                                  var_dump($found);





                                                                                  share|improve this answer













                                                                                  $a = ['x' => ['eee', 'ccc'], 'b' => ['zzz']];

                                                                                  $found = null;
                                                                                  $search = 'eee';

                                                                                  array_walk($a, function ($k, $v) use ($search, &$found)
                                                                                  if (in_array($search, $k))
                                                                                  $found = $v;

                                                                                  );

                                                                                  var_dump($found);






                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Nov 24 '15 at 23:43









                                                                                  klayklay

                                                                                  1,30111530




                                                                                  1,30111530





















                                                                                      1














                                                                                      I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not



                                                                                      $arr = array(
                                                                                      array(
                                                                                      'title' => 'abc'
                                                                                      )
                                                                                      );


                                                                                      Then i can use this



                                                                                      $res = array_search('abc', array_column($arr, 'title'));
                                                                                      if($res == '')
                                                                                      echo 'exists';
                                                                                      else
                                                                                      echo 'notExists';



                                                                                      I think This is the Most simple way to define






                                                                                      share|improve this answer



























                                                                                        1














                                                                                        I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not



                                                                                        $arr = array(
                                                                                        array(
                                                                                        'title' => 'abc'
                                                                                        )
                                                                                        );


                                                                                        Then i can use this



                                                                                        $res = array_search('abc', array_column($arr, 'title'));
                                                                                        if($res == '')
                                                                                        echo 'exists';
                                                                                        else
                                                                                        echo 'notExists';



                                                                                        I think This is the Most simple way to define






                                                                                        share|improve this answer

























                                                                                          1












                                                                                          1








                                                                                          1







                                                                                          I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not



                                                                                          $arr = array(
                                                                                          array(
                                                                                          'title' => 'abc'
                                                                                          )
                                                                                          );


                                                                                          Then i can use this



                                                                                          $res = array_search('abc', array_column($arr, 'title'));
                                                                                          if($res == '')
                                                                                          echo 'exists';
                                                                                          else
                                                                                          echo 'notExists';



                                                                                          I think This is the Most simple way to define






                                                                                          share|improve this answer













                                                                                          I want to check tha in the following array $arr is there 'abc' exists in sub arrays or not



                                                                                          $arr = array(
                                                                                          array(
                                                                                          'title' => 'abc'
                                                                                          )
                                                                                          );


                                                                                          Then i can use this



                                                                                          $res = array_search('abc', array_column($arr, 'title'));
                                                                                          if($res == '')
                                                                                          echo 'exists';
                                                                                          else
                                                                                          echo 'notExists';



                                                                                          I think This is the Most simple way to define







                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Oct 26 '17 at 11:52









                                                                                          M.suleman KhanM.suleman Khan

                                                                                          269214




                                                                                          269214





















                                                                                              1














                                                                                              Just share, maybe can like this.



                                                                                              if( ! function_exists('arraySearchMulti'))
                                                                                              function arraySearchMulti($search,$key,$array,$returnKey=false)

                                                                                              foreach ($array as $k => $val)
                                                                                              if (isset($val[$key]))
                                                                                              if ((string)$val[$key] == (string)$search)
                                                                                              return ($returnKey ? $k : $val);

                                                                                              else
                                                                                              return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);


                                                                                              return null;






                                                                                              share|improve this answer



























                                                                                                1














                                                                                                Just share, maybe can like this.



                                                                                                if( ! function_exists('arraySearchMulti'))
                                                                                                function arraySearchMulti($search,$key,$array,$returnKey=false)

                                                                                                foreach ($array as $k => $val)
                                                                                                if (isset($val[$key]))
                                                                                                if ((string)$val[$key] == (string)$search)
                                                                                                return ($returnKey ? $k : $val);

                                                                                                else
                                                                                                return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);


                                                                                                return null;






                                                                                                share|improve this answer

























                                                                                                  1












                                                                                                  1








                                                                                                  1







                                                                                                  Just share, maybe can like this.



                                                                                                  if( ! function_exists('arraySearchMulti'))
                                                                                                  function arraySearchMulti($search,$key,$array,$returnKey=false)

                                                                                                  foreach ($array as $k => $val)
                                                                                                  if (isset($val[$key]))
                                                                                                  if ((string)$val[$key] == (string)$search)
                                                                                                  return ($returnKey ? $k : $val);

                                                                                                  else
                                                                                                  return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);


                                                                                                  return null;






                                                                                                  share|improve this answer













                                                                                                  Just share, maybe can like this.



                                                                                                  if( ! function_exists('arraySearchMulti'))
                                                                                                  function arraySearchMulti($search,$key,$array,$returnKey=false)

                                                                                                  foreach ($array as $k => $val)
                                                                                                  if (isset($val[$key]))
                                                                                                  if ((string)$val[$key] == (string)$search)
                                                                                                  return ($returnKey ? $k : $val);

                                                                                                  else
                                                                                                  return (is_array($val) ? arraySearchMulti($search,$key,$val,$returnKey) : null);


                                                                                                  return null;







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Aug 22 '18 at 22:11









                                                                                                  Whendy TakashyWhendy Takashy

                                                                                                  246




                                                                                                  246





















                                                                                                      0














                                                                                                      Try this also



                                                                                                      function search_in_array($srchvalue, $array)

                                                                                                      if (is_array($array) && count($array) > 0)

                                                                                                      $foundkey = array_search($srchvalue, $array);
                                                                                                      if ($foundkey === FALSE)

                                                                                                      foreach ($array as $key => $value)

                                                                                                      if (is_array($value) && count($value) > 0)

                                                                                                      $foundkey = search_in_array($srchvalue, $value);
                                                                                                      if ($foundkey != FALSE)
                                                                                                      return $foundkey;



                                                                                                      else
                                                                                                      return $foundkey;







                                                                                                      share|improve this answer



























                                                                                                        0














                                                                                                        Try this also



                                                                                                        function search_in_array($srchvalue, $array)

                                                                                                        if (is_array($array) && count($array) > 0)

                                                                                                        $foundkey = array_search($srchvalue, $array);
                                                                                                        if ($foundkey === FALSE)

                                                                                                        foreach ($array as $key => $value)

                                                                                                        if (is_array($value) && count($value) > 0)

                                                                                                        $foundkey = search_in_array($srchvalue, $value);
                                                                                                        if ($foundkey != FALSE)
                                                                                                        return $foundkey;



                                                                                                        else
                                                                                                        return $foundkey;







                                                                                                        share|improve this answer

























                                                                                                          0












                                                                                                          0








                                                                                                          0







                                                                                                          Try this also



                                                                                                          function search_in_array($srchvalue, $array)

                                                                                                          if (is_array($array) && count($array) > 0)

                                                                                                          $foundkey = array_search($srchvalue, $array);
                                                                                                          if ($foundkey === FALSE)

                                                                                                          foreach ($array as $key => $value)

                                                                                                          if (is_array($value) && count($value) > 0)

                                                                                                          $foundkey = search_in_array($srchvalue, $value);
                                                                                                          if ($foundkey != FALSE)
                                                                                                          return $foundkey;



                                                                                                          else
                                                                                                          return $foundkey;







                                                                                                          share|improve this answer













                                                                                                          Try this also



                                                                                                          function search_in_array($srchvalue, $array)

                                                                                                          if (is_array($array) && count($array) > 0)

                                                                                                          $foundkey = array_search($srchvalue, $array);
                                                                                                          if ($foundkey === FALSE)

                                                                                                          foreach ($array as $key => $value)

                                                                                                          if (is_array($value) && count($value) > 0)

                                                                                                          $foundkey = search_in_array($srchvalue, $value);
                                                                                                          if ($foundkey != FALSE)
                                                                                                          return $foundkey;



                                                                                                          else
                                                                                                          return $foundkey;








                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered Oct 14 '14 at 11:50









                                                                                                          PravinSPravinS

                                                                                                          2,63031624




                                                                                                          2,63031624





















                                                                                                              0














                                                                                                              for( $i =0; $i < sizeof($allUsers); $i++)

                                                                                                              $NEEDLE1='firstname';
                                                                                                              $NEEDLE2='emailAddress';
                                                                                                              $sterm='Tofind';
                                                                                                              if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])



                                                                                                              Print_r($resultsMatched); //will give array for matched values even partially matched


                                                                                                              With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.






                                                                                                              share|improve this answer

























                                                                                                              • Please add a phrase to explain why this answers the question

                                                                                                                – Lorenz Meyer
                                                                                                                Feb 27 '15 at 15:41











                                                                                                              • whit help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question

                                                                                                                – sandeep sharma
                                                                                                                Feb 27 '15 at 17:16















                                                                                                              0














                                                                                                              for( $i =0; $i < sizeof($allUsers); $i++)

                                                                                                              $NEEDLE1='firstname';
                                                                                                              $NEEDLE2='emailAddress';
                                                                                                              $sterm='Tofind';
                                                                                                              if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])



                                                                                                              Print_r($resultsMatched); //will give array for matched values even partially matched


                                                                                                              With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.






                                                                                                              share|improve this answer

























                                                                                                              • Please add a phrase to explain why this answers the question

                                                                                                                – Lorenz Meyer
                                                                                                                Feb 27 '15 at 15:41











                                                                                                              • whit help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question

                                                                                                                – sandeep sharma
                                                                                                                Feb 27 '15 at 17:16













                                                                                                              0












                                                                                                              0








                                                                                                              0







                                                                                                              for( $i =0; $i < sizeof($allUsers); $i++)

                                                                                                              $NEEDLE1='firstname';
                                                                                                              $NEEDLE2='emailAddress';
                                                                                                              $sterm='Tofind';
                                                                                                              if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])



                                                                                                              Print_r($resultsMatched); //will give array for matched values even partially matched


                                                                                                              With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.






                                                                                                              share|improve this answer















                                                                                                              for( $i =0; $i < sizeof($allUsers); $i++)

                                                                                                              $NEEDLE1='firstname';
                                                                                                              $NEEDLE2='emailAddress';
                                                                                                              $sterm='Tofind';
                                                                                                              if(isset($allUsers[$i][$NEEDLE1]) && isset($allUsers[$i][$NEEDLE2])



                                                                                                              Print_r($resultsMatched); //will give array for matched values even partially matched


                                                                                                              With help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question.







                                                                                                              share|improve this answer














                                                                                                              share|improve this answer



                                                                                                              share|improve this answer








                                                                                                              edited Feb 27 '15 at 17:28









                                                                                                              Lorenz Meyer

                                                                                                              12.5k195293




                                                                                                              12.5k195293










                                                                                                              answered Feb 27 '15 at 15:13









                                                                                                              sandeep sharmasandeep sharma

                                                                                                              1




                                                                                                              1












                                                                                                              • Please add a phrase to explain why this answers the question

                                                                                                                – Lorenz Meyer
                                                                                                                Feb 27 '15 at 15:41











                                                                                                              • whit help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question

                                                                                                                – sandeep sharma
                                                                                                                Feb 27 '15 at 17:16

















                                                                                                              • Please add a phrase to explain why this answers the question

                                                                                                                – Lorenz Meyer
                                                                                                                Feb 27 '15 at 15:41











                                                                                                              • whit help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question

                                                                                                                – sandeep sharma
                                                                                                                Feb 27 '15 at 17:16
















                                                                                                              Please add a phrase to explain why this answers the question

                                                                                                              – Lorenz Meyer
                                                                                                              Feb 27 '15 at 15:41





                                                                                                              Please add a phrase to explain why this answers the question

                                                                                                              – Lorenz Meyer
                                                                                                              Feb 27 '15 at 15:41













                                                                                                              whit help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question

                                                                                                              – sandeep sharma
                                                                                                              Feb 27 '15 at 17:16





                                                                                                              whit help of above code one can find any(partially matched) data from any column in 2D array so user id can be found as required in question

                                                                                                              – sandeep sharma
                                                                                                              Feb 27 '15 at 17:16











                                                                                                              0














                                                                                                              Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:



                                                                                                               function searchArrayKeyVal($sKey, $id, $array) 
                                                                                                              foreach ($array as $key => $val)
                                                                                                              if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false)
                                                                                                              return $key;


                                                                                                              return false;



                                                                                                              For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"






                                                                                                              share|improve this answer





























                                                                                                                0














                                                                                                                Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:



                                                                                                                 function searchArrayKeyVal($sKey, $id, $array) 
                                                                                                                foreach ($array as $key => $val)
                                                                                                                if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false)
                                                                                                                return $key;


                                                                                                                return false;



                                                                                                                For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"






                                                                                                                share|improve this answer



























                                                                                                                  0












                                                                                                                  0








                                                                                                                  0







                                                                                                                  Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:



                                                                                                                   function searchArrayKeyVal($sKey, $id, $array) 
                                                                                                                  foreach ($array as $key => $val)
                                                                                                                  if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false)
                                                                                                                  return $key;


                                                                                                                  return false;



                                                                                                                  For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"






                                                                                                                  share|improve this answer















                                                                                                                  Expanding on the function @mayhem created, this example would be more of a "fuzzy" search in case you just want to match part (most) of a search string:



                                                                                                                   function searchArrayKeyVal($sKey, $id, $array) 
                                                                                                                  foreach ($array as $key => $val)
                                                                                                                  if (strpos(strtolower($val[$sKey]), strtolower(trim($id))) !== false)
                                                                                                                  return $key;


                                                                                                                  return false;



                                                                                                                  For example the value in the array is Welcome to New York! and you wanted the first instance of just "New York!"







                                                                                                                  share|improve this answer














                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer








                                                                                                                  edited Sep 21 '16 at 20:40

























                                                                                                                  answered Sep 21 '16 at 20:13









                                                                                                                  Mike QMike Q

                                                                                                                  2,59812537




                                                                                                                  2,59812537





















                                                                                                                      0














                                                                                                                      Try this



                                                                                                                      <?php
                                                                                                                      function recursive_array_search($needle,$haystack)
                                                                                                                      foreach($haystack as $key=>$value)
                                                                                                                      $current_key=$key;
                                                                                                                      if($needle===$value OR (is_array($value) &&
                                                                                                                      recursive_array_search($needle,$value) !== false))
                                                                                                                      return $current_key;


                                                                                                                      return false;

                                                                                                                      ?>





                                                                                                                      share|improve this answer





























                                                                                                                        0














                                                                                                                        Try this



                                                                                                                        <?php
                                                                                                                        function recursive_array_search($needle,$haystack)
                                                                                                                        foreach($haystack as $key=>$value)
                                                                                                                        $current_key=$key;
                                                                                                                        if($needle===$value OR (is_array($value) &&
                                                                                                                        recursive_array_search($needle,$value) !== false))
                                                                                                                        return $current_key;


                                                                                                                        return false;

                                                                                                                        ?>





                                                                                                                        share|improve this answer



























                                                                                                                          0












                                                                                                                          0








                                                                                                                          0







                                                                                                                          Try this



                                                                                                                          <?php
                                                                                                                          function recursive_array_search($needle,$haystack)
                                                                                                                          foreach($haystack as $key=>$value)
                                                                                                                          $current_key=$key;
                                                                                                                          if($needle===$value OR (is_array($value) &&
                                                                                                                          recursive_array_search($needle,$value) !== false))
                                                                                                                          return $current_key;


                                                                                                                          return false;

                                                                                                                          ?>





                                                                                                                          share|improve this answer















                                                                                                                          Try this



                                                                                                                          <?php
                                                                                                                          function recursive_array_search($needle,$haystack)
                                                                                                                          foreach($haystack as $key=>$value)
                                                                                                                          $current_key=$key;
                                                                                                                          if($needle===$value OR (is_array($value) &&
                                                                                                                          recursive_array_search($needle,$value) !== false))
                                                                                                                          return $current_key;


                                                                                                                          return false;

                                                                                                                          ?>






                                                                                                                          share|improve this answer














                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer








                                                                                                                          edited May 26 '17 at 16:10

























                                                                                                                          answered May 26 '17 at 15:39









                                                                                                                          Maurizio RicciMaurizio Ricci

                                                                                                                          19217




                                                                                                                          19217





















                                                                                                                              0














                                                                                                                              $search1 = 'demo';
                                                                                                                              $search2 = 'bob';
                                                                                                                              $arr = array('0' => 'hello','1' => 'test','2' => 'john','3' => array('0' => 'martin', '1' => 'bob'),'4' => 'demo');
                                                                                                                              foreach ($arr as $value)
                                                                                                                              if (is_array($value))
                                                                                                                              if (in_array($search2, $value))
                                                                                                                              echo "successsfully";
                                                                                                                              //execute your code

                                                                                                                              else
                                                                                                                              if ($value == $search1)
                                                                                                                              echo "success";








                                                                                                                              share|improve this answer





























                                                                                                                                0














                                                                                                                                $search1 = 'demo';
                                                                                                                                $search2 = 'bob';
                                                                                                                                $arr = array('0' => 'hello','1' => 'test','2' => 'john','3' => array('0' => 'martin', '1' => 'bob'),'4' => 'demo');
                                                                                                                                foreach ($arr as $value)
                                                                                                                                if (is_array($value))
                                                                                                                                if (in_array($search2, $value))
                                                                                                                                echo "successsfully";
                                                                                                                                //execute your code

                                                                                                                                else
                                                                                                                                if ($value == $search1)
                                                                                                                                echo "success";








                                                                                                                                share|improve this answer



























                                                                                                                                  0












                                                                                                                                  0








                                                                                                                                  0







                                                                                                                                  $search1 = 'demo';
                                                                                                                                  $search2 = 'bob';
                                                                                                                                  $arr = array('0' => 'hello','1' => 'test','2' => 'john','3' => array('0' => 'martin', '1' => 'bob'),'4' => 'demo');
                                                                                                                                  foreach ($arr as $value)
                                                                                                                                  if (is_array($value))
                                                                                                                                  if (in_array($search2, $value))
                                                                                                                                  echo "successsfully";
                                                                                                                                  //execute your code

                                                                                                                                  else
                                                                                                                                  if ($value == $search1)
                                                                                                                                  echo "success";








                                                                                                                                  share|improve this answer















                                                                                                                                  $search1 = 'demo';
                                                                                                                                  $search2 = 'bob';
                                                                                                                                  $arr = array('0' => 'hello','1' => 'test','2' => 'john','3' => array('0' => 'martin', '1' => 'bob'),'4' => 'demo');
                                                                                                                                  foreach ($arr as $value)
                                                                                                                                  if (is_array($value))
                                                                                                                                  if (in_array($search2, $value))
                                                                                                                                  echo "successsfully";
                                                                                                                                  //execute your code

                                                                                                                                  else
                                                                                                                                  if ($value == $search1)
                                                                                                                                  echo "success";









                                                                                                                                  share|improve this answer














                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer








                                                                                                                                  edited Aug 9 '17 at 9:17

























                                                                                                                                  answered Aug 9 '17 at 9:11









                                                                                                                                  BhavyeshBhavyesh

                                                                                                                                  113




                                                                                                                                  113





















                                                                                                                                      0














                                                                                                                                      If question i.e.



                                                                                                                                      $a = [
                                                                                                                                      [
                                                                                                                                      "_id" => "5a96933414d48831a41901f2",
                                                                                                                                      "discount_amount" => 3.29,
                                                                                                                                      "discount_id" => "5a92656a14d488570c2c44a2",
                                                                                                                                      ],
                                                                                                                                      [
                                                                                                                                      "_id" => "5a9790fd14d48879cf16a9e8",
                                                                                                                                      "discount_amount" => 4.53,
                                                                                                                                      "discount_id" => "5a9265b914d488548513b122",
                                                                                                                                      ],
                                                                                                                                      [
                                                                                                                                      "_id" => "5a98083614d488191304b6c3",
                                                                                                                                      "discount_amount" => 15.24,
                                                                                                                                      "discount_id" => "5a92806a14d48858ff5c2ec3",
                                                                                                                                      ],
                                                                                                                                      [
                                                                                                                                      "_id" => "5a982a4914d48824721eafe3",
                                                                                                                                      "discount_amount" => 45.74,
                                                                                                                                      "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                      ],
                                                                                                                                      [
                                                                                                                                      "_id" => "5a982a4914d48824721eafe55",
                                                                                                                                      "discount_amount" => 10.26,
                                                                                                                                      "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                      ],
                                                                                                                                      ];


                                                                                                                                      Ans:



                                                                                                                                      function searchForId($id, $array) 
                                                                                                                                      $did=0;
                                                                                                                                      $dia=0;
                                                                                                                                      foreach ($array as $key => $val)
                                                                                                                                      if ($val['discount_id'] === $id)
                                                                                                                                      $dia +=$val['discount_amount'];
                                                                                                                                      $did++;


                                                                                                                                      if($dia != '')
                                                                                                                                      echo $dia;
                                                                                                                                      var_dump($did);

                                                                                                                                      return null;
                                                                                                                                      ;
                                                                                                                                      print_r(searchForId('5a928ce414d488609e73b443',$a));





                                                                                                                                      share|improve this answer



























                                                                                                                                        0














                                                                                                                                        If question i.e.



                                                                                                                                        $a = [
                                                                                                                                        [
                                                                                                                                        "_id" => "5a96933414d48831a41901f2",
                                                                                                                                        "discount_amount" => 3.29,
                                                                                                                                        "discount_id" => "5a92656a14d488570c2c44a2",
                                                                                                                                        ],
                                                                                                                                        [
                                                                                                                                        "_id" => "5a9790fd14d48879cf16a9e8",
                                                                                                                                        "discount_amount" => 4.53,
                                                                                                                                        "discount_id" => "5a9265b914d488548513b122",
                                                                                                                                        ],
                                                                                                                                        [
                                                                                                                                        "_id" => "5a98083614d488191304b6c3",
                                                                                                                                        "discount_amount" => 15.24,
                                                                                                                                        "discount_id" => "5a92806a14d48858ff5c2ec3",
                                                                                                                                        ],
                                                                                                                                        [
                                                                                                                                        "_id" => "5a982a4914d48824721eafe3",
                                                                                                                                        "discount_amount" => 45.74,
                                                                                                                                        "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                        ],
                                                                                                                                        [
                                                                                                                                        "_id" => "5a982a4914d48824721eafe55",
                                                                                                                                        "discount_amount" => 10.26,
                                                                                                                                        "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                        ],
                                                                                                                                        ];


                                                                                                                                        Ans:



                                                                                                                                        function searchForId($id, $array) 
                                                                                                                                        $did=0;
                                                                                                                                        $dia=0;
                                                                                                                                        foreach ($array as $key => $val)
                                                                                                                                        if ($val['discount_id'] === $id)
                                                                                                                                        $dia +=$val['discount_amount'];
                                                                                                                                        $did++;


                                                                                                                                        if($dia != '')
                                                                                                                                        echo $dia;
                                                                                                                                        var_dump($did);

                                                                                                                                        return null;
                                                                                                                                        ;
                                                                                                                                        print_r(searchForId('5a928ce414d488609e73b443',$a));





                                                                                                                                        share|improve this answer

























                                                                                                                                          0












                                                                                                                                          0








                                                                                                                                          0







                                                                                                                                          If question i.e.



                                                                                                                                          $a = [
                                                                                                                                          [
                                                                                                                                          "_id" => "5a96933414d48831a41901f2",
                                                                                                                                          "discount_amount" => 3.29,
                                                                                                                                          "discount_id" => "5a92656a14d488570c2c44a2",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a9790fd14d48879cf16a9e8",
                                                                                                                                          "discount_amount" => 4.53,
                                                                                                                                          "discount_id" => "5a9265b914d488548513b122",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a98083614d488191304b6c3",
                                                                                                                                          "discount_amount" => 15.24,
                                                                                                                                          "discount_id" => "5a92806a14d48858ff5c2ec3",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a982a4914d48824721eafe3",
                                                                                                                                          "discount_amount" => 45.74,
                                                                                                                                          "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a982a4914d48824721eafe55",
                                                                                                                                          "discount_amount" => 10.26,
                                                                                                                                          "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                          ],
                                                                                                                                          ];


                                                                                                                                          Ans:



                                                                                                                                          function searchForId($id, $array) 
                                                                                                                                          $did=0;
                                                                                                                                          $dia=0;
                                                                                                                                          foreach ($array as $key => $val)
                                                                                                                                          if ($val['discount_id'] === $id)
                                                                                                                                          $dia +=$val['discount_amount'];
                                                                                                                                          $did++;


                                                                                                                                          if($dia != '')
                                                                                                                                          echo $dia;
                                                                                                                                          var_dump($did);

                                                                                                                                          return null;
                                                                                                                                          ;
                                                                                                                                          print_r(searchForId('5a928ce414d488609e73b443',$a));





                                                                                                                                          share|improve this answer













                                                                                                                                          If question i.e.



                                                                                                                                          $a = [
                                                                                                                                          [
                                                                                                                                          "_id" => "5a96933414d48831a41901f2",
                                                                                                                                          "discount_amount" => 3.29,
                                                                                                                                          "discount_id" => "5a92656a14d488570c2c44a2",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a9790fd14d48879cf16a9e8",
                                                                                                                                          "discount_amount" => 4.53,
                                                                                                                                          "discount_id" => "5a9265b914d488548513b122",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a98083614d488191304b6c3",
                                                                                                                                          "discount_amount" => 15.24,
                                                                                                                                          "discount_id" => "5a92806a14d48858ff5c2ec3",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a982a4914d48824721eafe3",
                                                                                                                                          "discount_amount" => 45.74,
                                                                                                                                          "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                          ],
                                                                                                                                          [
                                                                                                                                          "_id" => "5a982a4914d48824721eafe55",
                                                                                                                                          "discount_amount" => 10.26,
                                                                                                                                          "discount_id" => "5a928ce414d488609e73b443",
                                                                                                                                          ],
                                                                                                                                          ];


                                                                                                                                          Ans:



                                                                                                                                          function searchForId($id, $array) 
                                                                                                                                          $did=0;
                                                                                                                                          $dia=0;
                                                                                                                                          foreach ($array as $key => $val)
                                                                                                                                          if ($val['discount_id'] === $id)
                                                                                                                                          $dia +=$val['discount_amount'];
                                                                                                                                          $did++;


                                                                                                                                          if($dia != '')
                                                                                                                                          echo $dia;
                                                                                                                                          var_dump($did);

                                                                                                                                          return null;
                                                                                                                                          ;
                                                                                                                                          print_r(searchForId('5a928ce414d488609e73b443',$a));






                                                                                                                                          share|improve this answer












                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer










                                                                                                                                          answered Mar 13 '18 at 9:42









                                                                                                                                          Yuvraj Singh ShekhawatYuvraj Singh Shekhawat

                                                                                                                                          7013




                                                                                                                                          7013













                                                                                                                                              這個網誌中的熱門文章

                                                                                                                                              How to read a connectionString WITH PROVIDER in .NET Core?

                                                                                                                                              In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

                                                                                                                                              Museum of Modern and Contemporary Art of Trento and Rovereto