Search for a key in an array, recursively

php recursive loop through multidimensional array
php get array($key by value multidimensional)
php array map recursive
php recursive function return array
php find key in array
recursive array
php find key in multidimensional array
php multidimensional array set value as $key
private function find($needle, $haystack) {
    foreach ($haystack as $name => $file) {
        if ($needle == $name) {
            return $file;
        } else if(is_array($file)) { //is folder
            return $this->find($needle, $file); //file is the new haystack
        }               
    }

    return "did not find";
}

Hey, this method searches for a specific key in an associative array and returns the value associated with it. There's some problem with the recursion. Any clue?

Maybe it's overkill, but it's funny to use RecursiveIterators :)

UPDATE: Maybe it was overkill with old versions of PHP, but with >=5.6 (specially with 7.0) I would totally use this without doubt.

function recursiveFind(array $haystack, $needle)
{
    $iterator  = new RecursiveArrayIterator($haystack);
    $recursive = new RecursiveIteratorIterator(
        $iterator,
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            return $value;
        }
    }
}

UPDATE: Also, as of PHP 5.6, with generators you can easily iterate over all elements which pass the filter, not only the first one:

function recursiveFind(array $haystack, $needle)
{
    $iterator  = new RecursiveArrayIterator($haystack);
    $recursive = new RecursiveIteratorIterator(
        $iterator,
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            yield $value;
        }
    }
}

// Usage
foreach (recursiveFind($haystack, $needle) as $value) {
    // Use `$value` here
}

array_walk_recursive - Manual, array_walk_recursive — Apply a user function recursively to every member of an array The array parameter's value being the first, and the key/index second. I was looking for how to change values of array since you can't pass array by� Find values in JSON by key, recursively. GitHub Gist: instantly share code, notes, and snippets.

function array_search_key( $needle_key, $array ) {
  foreach($array AS $key=>$value){
    if($key == $needle_key) return $value;
    if(is_array($value)){
      if( ($result = array_search_key($needle_key,$value)) !== false)
        return $result;
    }
  }
  return false;
} 

this will work !

you need to stop the recursive deep search, by return false and then check it in the function.

you can find more examples of functions (like using RecursiveArrayIterator and more) in this link : http://php.net/manual/en/function.array-search.php

Recursive program to linearly search an element in a given array , Given an unsorted array and an element x, search x in given array. Write recursive C code for this. If element is not present, return -1. Recommended: Please try� The answer provided by xPheRe was extremely helpful, but didn't quite solve the problem in my implementation. There are multiple nested associative arrays in our data structure, and there may be multiple occurrences of any given key.

The answer provided by xPheRe was extremely helpful, but didn't quite solve the problem in my implementation. There are multiple nested associative arrays in our data structure, and there may be multiple occurrences of any given key.

In order to suit our purposes, I needed to implement a holder array that was updated while traversing the entire structure, instead of returning on the first match. The real work was provided by another poster, but I wanted to say thanks and share the final step that I had to cover.

public function recursiveFind(array $array, $needle)
{
    $iterator  = new RecursiveArrayIterator($array);
    $recursive = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
    $aHitList = array();
    foreach ($recursive as $key => $value) {
        if ($key === $needle) {
            array_push($aHitList, $value);
        }
    }
    return $aHitList;
}

Recursively search for a key in a PHP multidimensional array , * Recursively searches a multidimensional array for a key and optional value and returns the path as a string representation or subset of the array� Recursively deleting elements from an array I had a need recently to delete items from a nested associative array and also any empty sub-arrays. My initial thought was to use array_walk_recursive , but this doesn’t work as you can’t unset nested elements and you only have access to the leaves.

try this:

array_walk_recursive(
    $arrayToFindKey, 
    function($value, $key, $matchingKey){
        return (strcasecmp($key, $matchingKey) == 0)? true : false;
    }
    , 'matchingKeyValue'
);

Recursive isset or array_key_exists - PHP, so you are passing the list of keys you want to search for; what about the array you are trying to search in? Is it local to the function or also passed� Recursive function Linear Search ; if else statement ; How Program Works. Program takes size of array; Input elements in array; Passing array, key and size to the recursive function recursiveLinearSearch(int array[],int key, int size) Recursive function calls it self until certain conditions fulfill ; Function returns 1 if record found in array else returns -1

The best solution above misses the case if the key is repeated and only returns the first value, here I get all the values in an array instead:

function recursiveFind(array $array, $needle) {
  $iterator = new RecursiveArrayIterator($array);
  $recursive = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
  $return = [];
  foreach ($recursive as $key => $value) {
    if ($key === $needle) {
      $return[] = $value;
    }
  } 
  return $return;
}

C Program using Recursion to Search an Element in Array , printf("\nEnter the key to search: ");; scanf("%d", &key);; while (index > 0); {; index = search(list, index - 1, key);; /* In an array first position is indexed by 0 */ The index we are looking for (the key) In the method, the key is compared against a candidate key, which is the middle element of the current array. As you recursively chop the array in half, this

Get Array Values Recursively with PHP, The known valid array is actually a key=>value array so unfortunately array_values wont help get the simple list I'd like. Instead a more advanced� Recursively Summing an Array in Java: Recursion is a very useful and time efficient procedure that can quickly solve a problem with very little code. Recursion involves the method you create calling itself shortening the original problem. For this example, we will be summing an array

PHP: Search element in array recursive � GitHub, it returns it's value or key. By default give true or false if key/value have been found. *. * @param array $array Array to search. * @param string $search What to� The downside to this approach is that you need to create a wrapper function for each function you might want to call. Instead, we can use PHP 5.3's inline function syntax to create a new version of array_walk_recursive. <?php /** * This function acts exactly like array_walk_recursive, except that it pretends that the function

Recursively traverses a multidimensional array in search of a , Recursively traverses a multidimensional array in search of a specific key and returns an array containing the keys that correspond to the path of the first found� Given a sorted array of integers and a target value, find out if a target exists in the array or not in O(log(n)) time using Binary Search Algorithm in C and Java. Binary Search is a divide and conquer algorithm. Like all divide and conquer algorithms, Binary Search first divides a large array into two smaller subarray

Comments
  • How come you don't know what level it's at?
  • Thank you. This saved me. Remember to change the === to == if you don't need to do a strict comparison of the key.
  • Careful, if the key appears multiple times in the recursion, this only gets the value of the first one. To get them all modify it like this: function recursiveFind(array $array, $needle) { $iterator = new RecursiveArrayIterator($array); $recursive = new RecursiveIteratorIterator( $iterator, RecursiveIteratorIterator::SELF_FIRST ); $return = []; foreach ($recursive as $key => $value) { if ($key === $needle) { $return[] = $value; } } return $return; }
  • After PHP 5.6 I'd use a generator for this, calling yield instead of return.
  • how would that be @xPheRe
  • it fails if key value is '0'/zero. use one bellow then: fn 'recursiveFind'.
  • array_walk_recursive is possibly one of the mose useless functions of php. It will skip all sub arrays, so if your $key is the key to another array you'll not find it