title: PHP - Find previous value in multidimensional array
body: <p>I have this array:</p>
  
  <pre><code>$test = array( "a" =&gt; "b",
                  "c" =&gt; array("foo" =&gt; "bar",
                                  "3" =&gt; "4",
                              ),
                "e" =&gt; "f",); 
  </code></pre>
  
  <p>I want to create a function that finds the previous value in this array, given a certain value, for example <code>find("bar", $test);</code> should return "b".</p>
  
  <p>This is what I got:</p>
  
  <pre><code>function find($needle, $array, $parent = NULL)
  {
  //moves the pointer until it reaches the desired value
    while (current($array) != $needle){
      //if current value is an array, apply this function recursively
      if (is_array(current($array))){
        $subarray = current($array);
      //passes the previous parent array 
        find($needle, $subarray, prev($array));
      }
      //once it reaches the end of the array, end the execution
      if(next($array) == FALSE){
        return;
      }
    }
    //once the pointer points to $needle, run find_prev()
    find_prev(prev($array), $parent);
  }
  
  function find_prev($prev, $parent = NULL)
  {
    // in case there is no previous value in array and there is a superior level 
    if (!$prev &amp;&amp; $parent) {
      find_prev($parent);
      return;
    }
  
    // in case previous value is an array 
    // find last value of that array
  
    if (is_array($prev) &amp;&amp; $prev){
      find_prev(end($prev), $parent));
      return;
    } else {
    $GLOBALS['pre'] = $prev;
    }
  }
  </code></pre>
  
  <p>For pedagogical reasons and since I have devoted some time to this function, it would be great if you could provide any hints about why this isn't working rather than any other simpler solution that you might have. </p>