Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have PHP boolean FALSE to be output as FALSE only [duplicate]

Tags:

php

Possible Duplicate:
transfer a Variable from php to js

This might seem trivial. I am setting a PHP variable's value as false. Then after some processing I am outputting some JavaScript variables in a script. This is the code

$a = true;
$b = false;
echo '<script type="text/javascript">
          var a = '.$a.';
          var b = '.$b.';
      </script>';

When the script finishes I get this output:

var a = 1;
var b = ;

So I get syntax error in JavaScript. Now the question is, how to have those values as true boolean values in JavaScript as well?

Intended output:

var a = true;
var b = false;

I don't want string like 'true' or 'false'...or 1 and 0, but boolean true and false only. Any help regarding this, also with some explanation as to why PHP behaves this way?

like image 261
Shades88 Avatar asked Jul 25 '12 06:07

Shades88


People also ask

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

How can check boolean value in if condition in PHP?

The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.

Is 1 true or false in PHP?

Value 0 and 1 is equal to false and true in php.

Is empty string false in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.


1 Answers

echo '<script type="text/javascript">
          var a = '.($a?"true":"false").';
          var b = '.($b?"true":"false").';
      </script>';

I suppose, You cant simply echo true/false to get the word, You need to convert it to string.

like image 158
dpitkevics Avatar answered Sep 20 '22 16:09

dpitkevics