Sam San
Sam San

Reputation: 6903

php - variable iteration in function

I wanted to have a result like this

50+2+2+2+2 = 58

But I'm getting these kind of result

50
2
2
2
2

these are my codes.

<?php

$height = 50;

echo $height;

function hey($x)
{
    return $height += $x;
}


$i = 4;

while($i != 0)
{
    echo "<br>".hey(2);

    $i--;
}

?>

Please take note that the location of my variable and loop must be and really meant at that position.

what do i need to change on my code. I am new in using php functions. thanks for the help.

Upvotes: 2

Views: 106

Answers (6)

SaidbakR
SaidbakR

Reputation: 13544

This is online demo: http://phpfiddle.org/main/code/6h1-x5z

    <?php
        function getResult($height = 50, $increment = 2, $times = 4){
         echo $height."+";
         $total = 0;
         for ($i = 0; $i < $times; $i++){
            $total += $increment;     
          if ($i != ($times-1)){
           echo $increment."+";
          }
          else{
           echo $increment." = ".($height+$total);
          }          
         }      
        }    
        //usage
        getResult(50,2,4);
//The print out: 50+2+2+2+2 = 58
    ?>

Upvotes: 0

Reinstar
Reinstar

Reputation: 146

I don't understand that you want, but if you need output like that, please try this code..

br mean go to bottom, so I delete it.

<?php
    $height = 50;

    echo $height;

    function hey($x)
    {

        echo " + $x";

        return $x;

    }

    $i = 4;

    while($i != 0)
    {
        $height += hey(2);

        $i--;
    }

    echo " = $height";
?>

Upvotes: 0

Lo&#239;c MICHEL
Lo&#239;c MICHEL

Reputation: 26150

this is scope problem :

function hey($x)
{
    global $height;
    return $height += $x;
}

Upvotes: 1

nickb
nickb

Reputation: 59699

In this function:

function hey($x)
{
    return $height += $x;
}

$height is not in scope, so it is undefined. You should pass it in:

function hey($x, $height)
{
    return $height += $x;
}

Then call it like this:

hey(2, $height);

Upvotes: 1

ethrbunny
ethrbunny

Reputation: 10469

Change to:

global $height;

then

while($i != 0)
{
    echo "+".hey(2);

    $i--;
}

echo "=" . $height;

Upvotes: 0

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

You can use a global variable like this try:

function hey($x)
{
    global $height;
    return $height += $x;
}

And print the variable height only after the called function. If you don't put global before the variable inside the function it the seems that you create a new variable inside your function. With global you tell to the server to take the variable that you have created outside the function

Upvotes: 2

Related Questions