Mohamed Said
Mohamed Said

Reputation: 4613

Doing many returns in a function?

I'm trying to return the value of a function in order to echo it with another function< here's the code.

foreach($id as $sid){
$test .= '<li '.$class.'><a href="'.$post_link.'">'.$post_title.'</a></li>';

return $test;
}

with the other function I echo the result of this function, when doing that it shows only the first result of the for loop. What's wrong with the code?

Upvotes: 0

Views: 70

Answers (3)

ohaal
ohaal

Reputation: 5268

You can only return once. Return ends the execution of the current function. To echo the result, do this:

foreach($id as $sid){
    echo '<li '.$class.'><a href="'.$post_link.'">'.$post_title.'</a></li>';
}

To only return once, put the return outside of the for loop:

foreach($id as $sid){
    $test .= '<li '.$class.'><a href="'.$post_link.'">'.$post_title.'</a></li>';
}
return $test;

Upvotes: 1

Ryan
Ryan

Reputation: 28217

Put your return outside the loop:

foreach($id as $sid){
  $test .= '<li '.$class.'><a href="'.$post_link.'">'.$post_title.'</a></li>';
}
return $test;

Upvotes: 2

Josh
Josh

Reputation: 8191

You need to move the return statement outside of the for loop.

foreach($id as $sid){
    $test .= '<li '.$class.'><a href="'.$post_link.'">'.$post_title.'</a></li>';
}

return $test;

A return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

Upvotes: 6

Related Questions