V
V
Viktor Volkov2018-03-18 11:33:59
PHP
Viktor Volkov, 2018-03-18 11:33:59

Why doesn't return work?

function encrypt($text, $n) {
  
  $len = strlen($text);
  
    for($i = 1; $i < $len; $i += 2){

    $str1 .= substr($text, $i, 1);
    }	
    for($i = 0; $i < $len; $i += 2){

    $str2 .= substr($text, $i, 1);
    }

  if($n > 0 ){
    $m = $n - 1;
    $text = $str1.$str2;		
    encrypt($text, $m);
    
  } else {
    //echo  $text.' '; //выводит правильный результат!
    return $text;
  }
  
}
  
echo encrypt('This is a test!', 2); // результата нет...

Encryption task, it is necessary to form a string from every second character of the source string. The argument specifies how many times to scroll the line through this mechanism (decided by recursion). The question is, why doesn't return work? moreover, if you output next to else, then you can see that the function worked correctly, and there is a result, but if you display the result of the function, then the screen is empty ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
twobomb, 2018-03-18
@VGVolkov

Do you have no error output?

function encrypt($text, $n) {	
$str1 = $str2 = "";
for($i = 0; $i < strlen($text); $i++)
  if($i%2 == 0)
    $str2 .= $text[$i];
  else
    $str1 .= $text[$i];
if($n > 0 )
  $text = encrypt($str1.$str2, $n - 1);	
return $text;
}
echo encrypt('This is a test!', 2);

D
doublench21, 2018-03-18
@doublench21

Who is error reporting for? You haven't defined $str1 and $str2 at all. Well, judging by the code that you threw.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question