jumbo_siopao
jumbo_siopao

Reputation: 157

How to update a php variable inside a variable

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>';
} 
?>

Upvotes: 0

Views: 39

Answers (1)

arkascha
arkascha

Reputation: 42984

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>';
} 

Upvotes: 2

Related Questions