Home » Php » php – Check if variable returns true

php – Check if variable returns true

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to echo ‘success’ if the variable is true. (I originally wrote “returns true” which only applies to functions.

$add_visits = add_post_meta($id, 'piwik_visits', $nb_visits, true);
if($add_visits == true){
         echo 'success';
}

Is this the equivalent of

$add_visits = add_post_meta($id, 'piwik_visits', $nb_visits, true);
if($add_visits){
         echo 'success';
}

Or does $add_visits exist whether it is ‘true’ or ‘false’;

How to&Answers:

Testing $var == true is the same than just testing $var.

You can read this SO question on comparison operator.
You can also read PHP manual on this topic.

Note: a variable does not return true. It is true, or it evaluates to true. However, a function returns true.

Answer:

You might want to consider:

if($add_visits === TRUE){
     echo 'success';
}

This will check that your value is TRUE and of type boolean, this is more secure. As is, your code will echo success in the event that $add_visits were to come back as the string “fail” which could easily result from your DB failing out after the request is sent.

Answer:

They’re the same.

This…

if ($add_visits == true)
    echo 'success';

…Is the same as:

if ($add_visits)
    echo 'success';

In the same fashion, you can also test if the condition is false like this:

if (!$add_visits)
    echo "it's false!";

Answer:

Yeah, that would work fine.

//true
if($variable) echo "success";
if($variable == true) echo "success";


//false
if(!$variable) echo "failure";
if($variable == false) echo "failure";

Answer:

The most secure way is using php validation. In case of a ajax post to php:

$isTrue=filter_var($_POST['isTrue'], FILTER_VALIDATE_BOOLEAN);

Answer:

if($add_visits === TRUE)

should do the trick.

Answer:

if (isset($add_visits) && $add_visits === TRUE){
     echo 'success';
}

Might seem redundant, but PHP will throw a Notice if $add_visits isn’t set. This would be the safest way to test if a variable is true.