2

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.

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is a good answer in this scenario, but I would generally avoid the use of global if possible.
1

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);

Comments

1

this is scope problem :

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

Comments

0

Change to:

global $height;

then

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

    $i--;
}

echo "=" . $height;

Comments

0

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";
?>

Comments

0

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
    ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.