Reputation: 946
My main question is, why the below code prints out:
false
boolean value true
I would expect the variable "boolean" value is also false
I want to store some data in javascript and later use it in PHP, is it even possible?
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Storage test?</title>
</head>
<body>
<script type='text/javascript'>
localStorage.save = 'false';
</script>
<?php
$boolean = "<script type='text/javascript'>" .
"document.write(localStorage.save);".
"</script>";
echo $boolean;
if($boolean = 'true'){
echo "<p>boolean value true</p>";
} else {
echo "<p>boolean value false</p>";
}
?>
</body>
Upvotes: 0
Views: 9580
Reputation: 108
Using =
will only assign $boolean with that value and will return true because it's not false
, 0
, or null
. Try using ==
or ===
. :)
Upvotes: 0
Reputation: 601
One =
is to assign, comparison is either ==
or ===
.
This example displays "Hello":
<?php
function getData()
{
return 'Hello';
}
if ($data = getData()) {
echo $data;
}
This example displays "23":
<?php
function getData()
{
return 'Hello';
}
$data = getData()
if ($data === 'hello') {
echo 1;
}
if ($data == 'hello') {
echo 2;
}
if ($data === 'Hello') {
echo 3;
}
Upvotes: 0
Reputation: 26792
Like said, you're not comparing, but assigning because of the single equal sing =
in the if
statement.
Next to that you cannot directly read the localStorage from PHP. So even if you had a double equals ==
to compare, then it would still outout boolean value true
.
That is because you put a string
inside $Boolean
:
$boolean = "<script type='text/javascript'>document.write(localStorage.save);</script?";
You're not evaluating any JavaScript code like that.
When a PHP variable contains something, wether it be a string or number etc. it will always evaluate to true
inside an if
statement. Unless the value is either false
, 0
or null
.
To compare a real Boolean value you have to use an explicit compare. You do that with three equal signs ===
.
if ( $someBool === true )
{ // do stuff }
But no, you cannot directly get the localStorage value from JS to PHP. You'd need an Ajax call to pass it back to PHP. And I think that is what you're ultimately trying to do.
Upvotes: 4
Reputation: 74
I guess it's a typo in the if
you make
if($boolean == 'true'){
....
}
Upvotes: 0
Reputation: 1007
if($boolean = 'true'){ <-- this line
echo "<p>boolean value true</p>";
} else {
echo "<p>boolean value false</p>";
}
You are not comparing the $boolean variable with 'true', but assigning the value 'true'.
Try two equal signs.
I'm not even sure what you're doing is possible. But the equal sign is definately a problem.
Upvotes: 4