user2039290
user2039290

Reputation: 104

php recursive function return only false

function recursiveSearchKeyByVal($array, $needle) {
  //$k = false;
  foreach($array as $key => $val) {
    if( is_array($val) ) {
        $k = array_search($needle, $val);            
        if( $k ) {               
            #var_dump($k);   //<-- string(8) "12345678"      TRUE
            return $k;      //<-- bool(false)               FALSE ?????????
        } else {
           recursiveSearchKeyByVal($val, $needle);
        }
    }
  }
  return false;
}

$array = array( 'a'=>array(...), 'b'=>array( 'b1'=>array( '12345678'=>'abcdefgh' ), ...) );
var_dump( recursiveSearchKeyByVal($array, 'abcdefgh') );

I have this recursive function and I can't make it to return correct value... it only returns false.

Upvotes: 0

Views: 74

Answers (2)

KmeCnin
KmeCnin

Reputation: 527

This is working and I added the support if the value is at the very first deep of the array, like this you can find anywhere it's.

function recursiveSearchKeyByVal($array, $needle) {
  $k = false;
  foreach($array as $key => $val) {
    if( is_array($val) ) {
        $k = array_search($needle, $val);            
        if( !$k ) {
           $k = recursiveSearchKeyByVal($val, $needle);
        }
    } elseif ($needle == $val) {
        $k = $key;
    }
  }
  return $k;
}

Test here : demo

Upvotes: 0

ventaquil
ventaquil

Reputation: 2848

Heh, you call your function. When you call your function you will called again and again. But when it will return another value than false, it's been deeper than one execution.

You need something like that:

function recursiveSearchKeyByVal($array, $needle) {
  $k = false;
  foreach($array as $key => $val) {
    if( is_array($val) ) {
        $k = array_search($needle, $val);            
        if( $k ) {               
            #var_dump($k);   //<-- string(8) "12345678"      TRUE
            return $k;      //<-- bool(false)               FALSE ?????????
        } else {
           $k = recursiveSearchKeyByVal($val, $needle);
        }
    }
  }
  return $k;
}

Upvotes: 1

Related Questions