0

I have the following code:

$var1 = 'Hello';
$var2 = $var1.' friend';

Inside the if statement, if submit is clicked, I want to update var1 to 'Hi' so I am expecting 'Hi friend' as output. But it was not working- 'Hello friend' is still the output. I want to call it via var2. How can var1 be updated which is in var2?

Here is my full code:

<?php 
$var1 = 'Hello';
$var2 = $var1.' friend';

if(isset($_POST['submit'])) {
    $var1 = 'Hi';
    echo $var2;

} else{ 
echo '<form method="post" action="'. $_SERVER['PHP_SELF'] .'">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br> </form>';
} 
?>
2
  • 1
    you must repeat the code .. $var1 = 'Hi'; echo $var1 . $var2; once you have assigned $var1.' friend'; to $var2 .. the value is fixed (assigned ) to $var2 .. and if you want a new one you must reassign Commented Mar 29, 2018 at 16:26
  • 1
    Maybe you should use a function for that. You can't do it this way Commented Mar 29, 2018 at 16:28

1 Answer 1

2

No, that won't work, you have a miss conception of how things function. $var2 = $var1.' friend'; will assign a value immediately to ??$var2??, not a formular or something evaluated later. So $var2 contains whatever $var1 holds at the time of the assignment.

What you are looking for is a function:

<?php 

function greetWithPhrase($phrase) {
  return $phrase . ' friend';
}

$var1 = 'Hello';

if(isset($_POST['submit'])) {
    $var1 = 'Hi';
    echo greetWithPhrase($var1);    
} else{ 
  echo '<form method="post" action="'. $_SERVER['PHP_SELF'] .'">
  <input type="text" name="name"><br>
  <input type="submit" name="submit" value="Submit Form"><br> </form>';
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense. Thanks for the explanation. Im new to php, coming from a java background :P

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.