How to Use Return Inside a Recursive Function in PHP

How to use return inside a recursive function in PHP

You need to return the generated number from your recursive call too, like:

function generate_barcode() {
$barcode = rand(1, 10);
$bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
if ($bquery == 1) {
return generate_barcode(); // changed!
}
else {
return $barcode;
}
}

(You should include some kind of exit for the case that all numbers are 'taken'. This current version will call itself recursively until the PHP recursion limit is reached and will then throw an error.)

Return inside PHP recursive function

Your code is not working because a function should always have a return value - in recursion it is required:

function test($menu) {

$url = "test.com/accounts/overview/";

foreach($menu as $data) {

if( is_array($data) &&
isset($data["t_link"]) &&
$data["t_link"] === $url ) {
return $data["t_icon"];
}
else if (is_array($data)) {
$result = test($data); //Get result back from function

//If it's NOT NULL call the function again (test($data))
//
//(down below returns null when looped through
//everything recursively)
//
if ($result !== null) {
return $result;
}
}

}

return null;
}

Here's another way of achieving what you want OOP-style:

The idea behind this solution is to create a two-level array (no more, no less nr of levels) and grab data from that new array.

class Searcher {
private $new_arr = array();
private $icon = '';

//array_walk_recursive goes through your array recursively
//and calls the getdata-method in the class. This method creates
//a new array with strings (not arrays) from supplied $array ($menu in your case)
public function __construct($array, $search_url) {
array_walk_recursive($array, array($this, 'getdata'));
$key = array_search($search_url, $this->new_arr['t_link']);
$this->icon = $this->new_arr['t_icon'][$key];
}

public function geticon() {
return $this->icon;
}

public function getdata($item, $key) {
if (!is_array($item)) {
$this->new_arr[$key][] = $item;
}
}

}

//Implementation (usage) of above class
$search = new Searcher($menu, 'test.com/accounts/overview/');
$icon = $search->geticon();
echo 'ICON=' . $icon; //Would echo out 'fa fa-book'

Further explanation:

Based on your $menu - array the class will create an array like this ($this->new_arr):

Array
(
[t_link] => Array
(
[0] => test.com
[1] => test.com/accounts
[2] => test.com/accounts/overview/
)

[t_icon] => Array
(
[0] => fa fa-dashboard
[1] => fa fa-books
[2] => fa fa-book
)

)

All the keys are related to eachother in the new array. This is set with $this->new_arr[$key][] = $item; within the getdata() method. This is based on the fact it must be equal number of t_link-keys and t_icon-keys in the array.

Because of this:

$this->new_arr[0]['t_link'] is related to $this->new_arr[0]['t_icon'];
$this->new_arr[1]['t_link'] is related to $this->new_arr[1]['t_icon'];
$this->new_arr[2]['t_link'] is related to $this->new_arr[2]['t_icon'];
etc.. (not more in your example)

When having this code:

$key = array_search($search_url, $this->new_arr['t_link']);

it would give the key 2 if you have supplied $search_url to test.com/accounts/overview/

Therefore:

$this->icon = $this->new_arr['t_icon'][$key];

is set to fa fa-book

Function doesn't return value in recursive function php

Just return the value from the recursive call in order to catch the result.

EDIT:

Here is a new way of handling your code.

  • If the number you are passing is greater than five then subtract 1
    every recursive call.
  • If the number is lower than five than add 1 every recursive call.
  • Otherwise it returns 5.

So when it reaches five, the output will be for example echo012345 or echo98765.


If you want to limit the output to echo5, then you should wrap $a .= $i with an if statement to check if ($i == 5).

<?php
function debug($a, $i) {
$a .= $i;

if ($i > 5) {
$i--;
return debug($a, $i);
} elseif ($i < 5) {
$i++;
return debug($a, $i);
}
return $a;
}

echo debug('echo', 10);

?>

How I use return inside a recursive functions in php

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;
}

PHP recursive function return value

You're not returning the text properly, e.g.,

    } else {
echo 'else 1<br />';
return $str; // <--- nothing in the 'parent' caller catches this, so it's lost
}

Anywhere you do recursion and need to return a value, you must capture/return the recursive call itself:

    return check_length(substr($str, 0, -1), $max, $size, true);

or

    $newstr = check_length(...);
return $newstr;

Recursive function not returning anything

You have to use return while calling your function recursively otherwise the intermediary results will be lost.

if (checkIdDB($id_conf, $world) === true) {
//echo "chek again $id_conf";
return checkIdExits($id_conf, $world, 1);
}

How to use a recursion function in PHP to increment the value on array and return total value from array

Code is in the C language as shown below.

Based on an old mathematical formula:

Sum of n numbers = sum of (n-1) numbers + nth term

Please adjust for array index, overshooting or it being less than 0.

int sum(int arr[], int arrlength)
{
if (arrlength == 0)
return 0;

return (sum(arr, arrlength - 1) + arr [arrlength]);
}

How can I return a variable at last call of recursive function?

Looks as though you need a couple of changes, first to return the built up string from the routine at the end...

        }
$str .= '</ul>';
}
return $str;
}

The second is where you call the routine recursively, you need to set the the return value to the string you are generating...

$str = $this->deneme($row['id'], $sub_mark, $str);


Related Topics



Leave a reply



Submit