How To Display Output With Return Using For Loop In PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

Display my output in PHP with a return in a loop

display my output in PHP with a return in a loop

In PHP, there are two basic ways to get output: 
  • echo.
  • print.

echo and print are  both used to output data to the screen.
differences :

   echo                           print                        
no return value                return value of 1 
take multiple parameters       take one argument. 
faster than print.      
 

for example:

<?php

echo "<h2>Hello world!</h2>";
print "Learn PHP from Bajarangisoft!";

?>
 

How can we view output  with a return in a loop.

first create function in that declare one variable as $output and assign empty string after that create for loop  using $i variable and for  each iteration $i get incremented and at the end of loop data get return when we call function.

for example:

 function myfunction()
        {
            $output = '';
            for ( $i = 1 ; $i <= 10 ; $i++ )//from 1 incremented upto 10 
            {
                $output .= $i;
            }
            return $output;
}

call function to display output:

echo myfunction();

Complete Code to display my output in PHP with a return in a loop :
<!DOCTYPE html>
<html>
<head>
    <title>Display my output in PHP with a return in a loop</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <br>
    <br>
    <div class="text-center">
        <h1>Display my output in PHP with a return in a loop</h1>
    </div>
    <br>
    <br>
    <div class="well">
        
        <?php
        echo "<h2>Hello world!</h2>";
        print "Learn PHP from Bajarangisoft!";

        function myfunction()
        {
            $output = '';
            for ( $i = 1 ; $i <= 10 ; $i++ )
            {
                $output .= $i;
            }
            return $output;
        }
        echo "<h1>".myfunction()."</h1>";
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post