Search code examples
phpvariablestextgetstore

PHP Set Variable if Empty?


I have this variable, let's say

$text

I also have a website, site.com/

I want to get this:

site.com/index.php?text=hello

And get the page to display "hello", and setting the variable $hello to store 'hello' if no other text is entered. Right now, I feel embarrased to ask this. This is really basic, and I have gotten it to work many times, but this time I don't know where I went wrong.

My code is:

$text = $_GET['text'];
    if ($text = ''){
    $text = 'hello';
    }
echo $text;

What's wrong with this?


Solution

  • = means assignment, while == means comparison.

    Another way to test if the $text is empty:

    $text = $_GET['text'];
        if (empty($text)){
           $text = 'hello';
        }
    echo $text;
    

    or directly

    if(!isset($_GET['text'])) {
      ...
    }