B
B
Bodya_idiot2020-05-05 19:10:42
PHP
Bodya_idiot, 2020-05-05 19:10:42

Why does return not return a value?

The question is why return does not return a result.
Example :

<?php

$a = 1;
function test($a) 
{
    if($a == 5) {
        return 'не возвращает значение';
    } else {
        $a += 1; 
        echo $a . '<br>'; // Это для проверки
        test($a);  // Пользуюсь рекурсией, но уже беру  $a с новым значением  
    }
}
$a = test($a);
echo $a;  // он должен выводить 5 но он ничего не выводит

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Samsonov, 2020-05-05
@Bodya_idiot

Because the value of the test function is not returned when called recursively. Should be like this

<?php
function test($a) 
{
    if($a === 5) {
        return 'не возвращает значение';
    }
    
   return test($a + 1);    // Здесь нужен return 
}

echo test(1);

sandbox.onlinephpfunctions.com/code/3473fa114823e1...

A
Andrey Pastukhov, 2020-05-05
@tyllo

return test($a); // Пользуюсь рекурсией, но уже беру $a с новым значением

A
anna_makeenko, 2020-05-05
@anna_makeenko

echo - Output one or more lines

https://www.php.net/manual/en/function.echo.php
return returns program control to the module from which the function was called. Program execution continues with the instruction following the call site.

https://www.php.net/manual/ru/function.return.php
Do you catch the difference?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question