PHP Set Variable if Empty?

60

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?

676

Answer

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'])) {
  ...
}
708

Answer

Solution:

if ($text = ''){

This is an affectationassignment, not a test.

if ($text == ''){ // should work :-)
878

Answer

Solution:

You did a tiny little mistake ;-)

If you want to compare things you need to use two equality signs. Otherwise it is a assignment.

if($text == '') {
    $text = 'name';
}

The assignment is always true since there is no problem writing a string to $text

281

Answer

Solution:

Use == operator for comparision...

People are also looking for solutions to the problem: php - Get respective part from string

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.