Home > Enterprise >  How I use return inside a recursive functions in php
How I use return inside a recursive functions in php

Time:05-14

I have a php recursive function as shown in the below:

function displayDropdown(&$catList, $parent,  $current=[], $level=0) {
  if ($parent==0) {
    foreach ($catList[$parent] as $catID=>$nm) {
      displayDropdown($catList, $catID, $current);
    }
  }
  else {        
    foreach ($catList[$parent] as $catID=>$nm) {
      $sel = (in_array($catID, $current)) ? " selected = 'selected'" : '';       
      
      echo "<option value='$catID' $sel>$nm</option>\n";        
      
      if (isset($catList[$catID])) {
        displayDropdown($catList, $catID, $current, $level 1); 
      }
    }
  }   
}

This function is working for me. but I want to get output from a variable instead of echoing inside the function. Actually I need to return option list from the funciton.

This is how I tried it, but it doesn't work for me.

function displayDropdown(&$catList, $parent,  $current=[], $level=0) {
  $optionsHTML = '';
  if ($parent==0) {
    foreach ($catList[$parent] as $catID=>$nm) {
      displayDropdown($catList, $catID, $current);
    }
  }
  else {        
    foreach ($catList[$parent] as $catID=>$nm) {
      $sel = (in_array($catID, $current)) ? " selected = 'selected'" : '';       

      $optionsHTML .= "<option value='$catID' $sel>$nm</option>\n";        
      
      if (isset($catList[$catID])) {
        displayDropdown($catList, $catID, $current, $level 1);
      }
    }
  } 

  //return displayDropdown($optionsHTML);
  return $optionsHTML;
}

UPDATE: This is how I call this function.

displayDropdown($catList, 0, [$cid])

This is how I create $catList array inside while loop with the result of a query.

while ($stmt->fetch()) {    
  $catList[$parent][$catID] = $name;    
}

Array structure as below:

Array
(
    [1] => Array
        (
            [2] => Uncategorized
            [3] => SHOW ITEMS
            [4] => HORN
            [5] => SWITCH
            [6] => LIGHT
        )

    [0] => Array
        (
            [1] => Products
        )
)
1

Hope somebody may help me out.

CodePudding user response:

you need also like this $optionsHTML .= displayDropdown(...)

function displayDropdown(&$catList, $parent,  $current=[], $level=0) {
  $optionsHTML = '';
  if ($parent==0) {
    foreach ($catList[$parent] as $catID=>$nm) {
      $optionsHTML .= displayDropdown($catList, $catID, $current);
    }
  }
  else {        
    foreach ($catList[$parent] as $catID=>$nm) {
      $sel = (in_array($catID, $current)) ? " selected = 'selected'" : '';       

      $optionsHTML .= "<option value='$catID' $sel>$nm</option>\n";        
      
      if (isset($catList[$catID])) {
        $optionsHTML .= displayDropdown($catList, $catID, $current, $level 1);
      }
    }
  } 

  return $optionsHTML;
}
  • Related