Search code examples
phprecursionstore

How to return the array in recursive function in php


I'm trying to handle the recursive array in PHP. But my code is working fine. Problem is I'm unable to store the results in one array and return.

See the code:

function array_recursion(array $myarray, array $searchterms){
   //empty array
   $tempArr = array();
       //loop through $myarray
            foreach ($myarray as $key => $value){
                if (is_array($value)){
                  array_recursion($value, $searchterms);
                } 
                else if (in_array($key, $searchterms)){
                  print str_replace("0:", "", ($key . ": " . $value . "\n"));
                }
            }
        }
   //Call the function
    $finalValue = array_recursion($arr, Array('VCHKEY','VOUCHERTYPENAME','VOUCHERNUMBER','PARTYNAME','NARRATION','REFERENCE','AMOUNT','VCHTYPE'));
    //but this should print empty array
    print_r($finalValue);die();

I want to use the below two lines in the above function

$tempArr[] = str_replace("0:", "", ($key . ": " . $value . "\n"));
return $tempArr;

What is the actual issue? Can anyone help to figure it out? Thanks in advance.


Solution

  • Finally i found the solution to return the value as array using recursion method.Check the below code.

     function array_value_recursive(array $key, array $arr){
        $val = array();
        array_walk_recursive($arr, function($va, $ke) use($key, &$val){
            if(in_array($ke,$key))
             array_push($val, $va);
        });
        return count($val) > 1 ? $val : array_pop($val);
      }
    

    Hope this will help someone.