AlxVallejo
AlxVallejo

Reputation: 3219

Check if variable returns true

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

Upvotes: 9

Views: 87652

Answers (8)

Nefeli Tech
Nefeli Tech

Reputation: 1

Noncompliant Code Example

if ($booleanVariable == true) { /* ... */ }
if ($booleanVariable != true) { /* ... */ }
if ($booleanVariable || false) { /* ... */ }

doSomething(!false);

Compliant Solution
if ($booleanVariable) { /* ... */ }
if (!$booleanVariable) { /* ... */ }
if ($booleanVariable) { /* ... */ }

doSomething(true);

Upvotes: 0

Flemming
Flemming

Reputation: 694

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

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

Upvotes: 2

cdmo
cdmo

Reputation: 1309

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.

Upvotes: 0

Jezen Thomas
Jezen Thomas

Reputation: 13800

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!";

Upvotes: 10

Dilvish5
Dilvish5

Reputation: 310

if($add_visits === TRUE)

should do the trick.

Upvotes: 2

usumoio
usumoio

Reputation: 3568

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.

Upvotes: 22

Ben
Ben

Reputation: 5777

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";

Upvotes: 1

Guillaume Poussel
Guillaume Poussel

Reputation: 9822

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.

Upvotes: 11

Related Questions