PHP - Why my function isnt returning anything - php

I have function calling itself. There is a number of max repeats and repeat counter. The function is calling itself until reaching a point where repeat counter is equal to max repeats. If I uncomment messages inside a function, I can see everything working as it should. But if I want to return an array of positions, there is no result:
function myFunction($positions, $maxRepeats, $repeatCounter = 0){
if($repeatCounter < $maxRepeats){
// echo 'Test message - loop ' . $repeatCounter;
$positions[] = array('title' => $repeatCounter);
$repeatCounter++;
myFunction($positions,$maxRepeats,$repeatCounter);
} else {
// echo 'Test message - end ' . $repeatCounter;
return $positions;
}
}
$positions = array();
$result = myFunction($positions,2);
print_r($result);
Thanks for any idea.

Because if this condition is true:
if($repeatCounter < $maxRepeats)
Then the function never encounters a return statement. It looks like you meant to return the recursive result:
return myFunction($positions,$maxRepeats,$repeatCounter);

Related

Function doesn't return value in recursive function php [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I'd like to return some value using a recursive function. Unfortunately the function doesn't return anything until I change return to echo.
Here is a similar function I created for better understanding.
function debug($a, $i) {
$a .= $i;
if ($i !== 5) {
$i++;
debug('echo', $i);
} else {
return $a; // expecting echo5 (echo works perfectly)
}
}
echo debug('echo', 0); // doesn't return anything
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);
?>
The function is working 100% as intended. You do not print the value simply because the function is "returning" it. If you want the value printed, then you must echo it as you've observed yourself.
Think of it this way:
Return - returns the value in raw data.
echo - prints stuff.
Also the way your recursive function works now, it only contains the return value within its scope, so the value is "dropped" when the execution is completed. That's why you won't be able to echo anything. When you echo inside the function, it's echoing the value before stopping the execution.
One way to circumvent this, is by adding a print parameter to the function if you wish for your value to be printed,
Example:
function debug($a, $i, $print=false) {
$a .= $i;
if($i < 5) {
$i++;
debug('echo', $i, $print);
} else{
if($print){
echo $a;
}
return $a;
}
}
debug('echo', 0, true);

Can echo true but wont return

Im trying to return true when my loop has finished but it does not seem to happen.
I can get it to echo true or false or any text but returning does nothing.
Wonder if anyone could explain why this is.
Here is the (kinda) function I have removed the data base calls and such as its not important.
function loop_me(){
// this part is not important...
$finished = false;
$done = 0;
$userC = 1000;
$page = 0;
$count = 10;
$array = array()
$data = array('1','2','3') // big array of data...
if($done < $userC){
for($i=0; $i<$count; $i++){
$array[] = $data[$i];
}
// bellow is the important part...
if($done >= $userC){
$finished = true;
}else{
$page++;
loop_me();
}
}
if($finished){
// If I echo true it outputs 1 (this is fine)
// if I return true I get nothing this is got good as I want to do an IF statement on the
// output, which I can't do if it does not.
echo(true);
}
}
Ok so the function with the issue is above but just to help you out, the basic idea of the function is that i loops thought an array of data (not showen above) but this data is paginated so it needs to go to the next 'page' once its finished with the first and there a few pages so what I want to do is when it has finished looping thought it all return true.
Might be a simple fix.
But I can't work it out.
You called 'loop_me()' recursively, but you need to return it.
}else{
$page++;
return loop_me();
}
and of course change echo to return too!
edit your echo (true); to something like: return true; then call your function:
$var = loop_me();
echo $var; // If a success you should see true.
You should also consider adding a return false if there is a problem when calling your defined function.

Php index of element in the array, update element

for some reason $post is always < 0. The indoxOf function works great. I use it on ohter codes and it works great
for some reason even after I add the element like this array_push($groups, $tempDon); on the next loop i continues to return -1
$donations = $this->getInstitutionDonations($post->ID);
$groups=array();
foreach( $donations as $don ) : setup_postdata($don);
$pos = $this->indexOf($don, $groups);
print_r($pos);
if($pos < 0)
{
$tempDom = $don;
$tempDon->count = 1;
array_push($groups, $tempDon);
}
else
{
$tempDom = $groups[$pos];
$tempDon->count++;
array_splice($tempDon);
array_push($groups, $tempDon);
echo '<br><br><br>ahhhhhhhhhh<br><br>';
}
endforeach;
protected function indexOf($needle, $haystack) { // conversion of JavaScripts most awesome
for ($i=0;$i<count($haystack);$i++) { // indexOf function. Searches an array for
if ($haystack[$i] == $needle) { // a value and returns the index of the *first*
return $i; // occurance
}
}
return -1;
}
This looks like an issue of poor proofreading to me (note $tempDom vs $tempDon):
$tempDom = $don;
$tempDon->count = 1;
array_push($groups, $tempDon);
Your else block has similar issues.
I also completely agree with #hakre's comment regarding syntax inconsistencies.
EDIT
I'd also like to recommend that you make use of PHP's built-in array_search function in the body of your indexOf method rather than rolling your own.

Function not returning a result [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
Here is a function in PHP that generates a random number between 1 and 15 and store that number in a array and keep calling itself to repeat until the array contains five elements, at which point, you can make it either print/echo out the elements of the array or return the array. My problem is that when I try to get it to return the array and assign it to the variable $result, I get nothing. Any ideas as to what's going on?
$storenumbers = array();
function storemynumbers($storenumbers){
$number = rand(1,15);
if(count($storenumbers) == 5){
echo "Done<br/>";
print_r($storenumbers);
//return $storenumbers;
}else{
echo $number."<br/>";
$storenumbers[] = $number;
storemynumbers($storenumbers);
}
}
//$result = storemynumbers($storenumbers);
//print_r($result);
storemynumbers($storenumbers);
Because you are only returning anything on the last run, which gets passed back to the next-to-last run, which is then dropped.
In your else block, try adding return in front of storemynumbers($storenumbers). This should pass the return value all the way back down the chain.
That said, why can't you just do:
$storenumbers = Array();
for( $i=0; $i<5; $i++) $storenumbers[] = rand(1,15);
print_r($storenumbers);
becouse you need to pass parameter by reference(& before parameter): like this:
function storemynumbers(&$storenumbers){
}
By default variables are local copy, so they not visible outside function.
missing return on the recursion. would be my guess.
$storenumbers = array();
function storemynumbers($storenumbers){
$number = rand(1,15);
if(count($storenumbers) == 5){
echo "Done<br/>";
print_r($storenumbers);
return $storenumbers;
}else{
echo $number."<br/>";
$storenumbers[] = $number;
return storemynumbers($storenumbers);
}
}
$result = storemynumbers($storenumbers);
print_r($result);
This is a easy way to create a array of $max random number between 1 and 15.
function storemynumbers($max, $start, $end) {
$store = array();
for( $i=0; $i<$max; $i++) {
$store[] = rand($start, $end);
}
return $store;
}
$result = storemynumbers(5, 1, 15);
print_r($result);
You could also use a reference to a variable

How do I store the results of this recursive function?

I have the following PHP code which works out the possible combinations from a set of arrays:
function showCombinations($string, $traits, $i){
if($i >= count($traits)){
echo trim($string) . '<br>';
}else{
foreach($traits[$i] as $trait){
showCombinations("$string$trait", $traits, $i + 1);
}
}
}
$traits = array(
array('1','2'),
array('1','2','3'),
array('1','2','3')
);
showCombinations('', $traits, 0);
However, my problem is that I need to store the results in an array for processing later rather than just print them out but I can't see how this can be done without using a global variable.
Does anyone know of an alternative way to achieve something similar or modify this to give me results I can use?
Return them. Make showCombinations() return a list of items. In the first case you only return one item, in the other recursive case you return a list with all the returned lists merged. For example:
function showCombinations(...) {
$result = array();
if (...) {
$result[] = $item;
}
else {
foreach (...) {
$result = array_merge($result, showCombinations(...));
}
}
return $result;
}
In addition to the other answers, you could pass the address of an array around inside your function, but honestly this isn't nearly the best way to do it.
Using the variable scope modifier static could work. Alternatively, you could employ references, but that's just one more variable to pass. This works with "return syntax".
function showCombinations($string, $traits, $i){
static $finalTraits;
if (!is_array($finalTraits)) {
$finalTraits = array();
}
if($i >= count($traits)){
//echo trim($string) . '<br>';
$finalTraits[] = $string;
} else {
foreach($traits[$i] as $trait){
showCombinations("$string$trait", $traits, $i + 1);
}
}
return $finalTraits;
}
$traits = array(
array('1','2'),
array('1','2','3'),
array('1','2','3')
);
echo join("<br>\n",showCombinations('', $traits, 0));
Of course, this will work as expected exactly once, before the static nature of the variable catches up with you. Therefore, this is probably a better solution:
function showCombinations($string, $traits, $i){
$finalTraits = array();
if($i >= count($traits)){
$finalTraits[] = $string;
} else {
foreach($traits[$i] as $trait){
$finalTraits = array_merge(
$finalTraits,
showCombinations("$string$trait", $traits, $i + 1)
);
}
}
return $finalTraits;
}
although the solution by Lukáš is the purest as it has no side effects, it may be ineffective on large inputs, because it forces the engine to constantly generate new arrays. There are two more ways that seem to be less memory-consuming
have a results array passed by reference and replace the echo call with $result[]=
(preferred) wrap the whole story into a class and use $this->result when appropriate
the class approach is especially nice when used together with php iterators
public function pageslug_genrator($slug,$cat){
$page_check=$this->ci->cms_model->show_page($slug);
if($page_check[0]->page_parents != 0 ){
$page_checks=$this->ci->page_model->page_list($page_check[0]->page_parents);
$cat[]=$page_checks['re_page'][0]->page_slug;
$this->pageslug_genrator($page_checks['re_page'][0]->page_slug,$cat);
}
else
{
return $cat;
}
}
this function doesnt return any value but when i m doing print_r $cat it re
store the results in a $_SESSION variable.

Categories