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>
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.
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.
I guess it's a typo in the if you make
if($boolean == 'true'){
....
}
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;
}
Using = will only assign $boolean with that value and will return true because it's not false, 0, or null. Try using == or ===. :)
Related
I'm trying to create a simple yes/no or true/false boolean type line to parse content depending on the answer.
Like this:
<?php
dangerous = "yes";
?>
<?php
dangerous = "no";
?>
A block down here similar to isset, that will parse if the answer above is yes, and to not appear if anything else other than yes is written.
<?php if dangerous = yes ?>
Dangerous content here.
<?php endif; ?>
I'm new to PHP, so I'm not sure what route to go with here.
Firstly, this line here will always evaluate to true, because you are using a single = which is an assignment operator:
if($dangerous = 'yes') // this will always be true
You need to use == for a comparison operator, or === for strict comparison which takes variable types and values into consideration as well. For more info on the difference between the comparison operators, see here.
The way you're doing it currently is pretty widely used, but is not the best practice. Your variable $dangerous will be set every time, and you need to check for the value of it to determine whether to evaluate your conditions or not:
if($dangerous == 'yes') {
// do dangerous stuff
}
Better practice, as you've said, is to use a boolean variable which will evaluate to true or false (above example in this same test will evaluate to true in both cases):
$dangerous = true; // or false;
if($dangerous) {
// do dangerous stuff
}
Likewise, if it's not dangerous:
if(!$dangerous) {
// pretty safe, but this will evaluate to true for false, null, zero etc
}
In this example, !$dangerous will evaluate to true when $dangerous is null, zero etc, so if you need a strict comparison for the value of false, you'll need the === comparison operator:
if($dangerous === false) {
// false evaluates to true when comparing for a false value
// false evaluates to false when comparing for a null value
}
Better to use a boolean variable over a string representation of a result in most cases. Something to keep in mind though is that if your your boolean variable represents the return of a function call, it might not always be consistent.
if($dangerous == "yes"){
//do something
} else {
//do something else
}
<?php
if($yes){
?>
<b>This is my HTML.</b>
<?php
}else{
?>
<b>This is other HTML.</b>
<?php
}
?>
<?php if ($dangerous === 'yes'): ?>
yes
<?php endif; ?>
<?php if ($dangerous == 'no'): ?>
no
<?php endif; ?>
The issue is the use of an assignment operator (=) when you should be using a comparison operator (== / ===) and comparing variables and value correctly.
For your case
<?php
if($dangerous === "yes"){
//Dangerous content here.
}
?>
Use code like this:
$dangerous = true; // or false if no
// check result
if ($dangerous) {
// dangerous!
}
Define the conditions for dangerous content and apply php expeptions:
if(dangerous){
try {
echo inverso(5) . "\n";
echo inverso(0) . "\n";
} catch (Exception $e) {
echo 'Excepción capturada: ', $e->getMessage(), "\n";
}
}
I'm getting really strange results on a php script that takes boolean input. The idea is that the data needs to be stored as either a 1 or a 0, but the input to the php script is a string in true/false format. Check this out:
<?php
function boolToBinary($str) {
echo $_POST['wants_sms'] . " " . $str;
die();
// posting this so that you can see what this function is supposed to do
// once it is debugged
if ($str == true) {
return 1;
} else {
return 0;
}
}
$gets_sms = boolToBinary($_POST['wants_sms']);
Here is the output from this function:
false true
How can that be??? Thanks for any advice.
EDIT: Solution: Still not sure why my output was flipped, but the fundamental problem is solved like this:
if ($str === 'true') {
return 1;
} else {
return 0;
}
Thanks to RocketHazmat for this.
http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
see this example:
var_dump((bool) "false"); // bool(true)
And the explanations:
When converting to boolean, the following values are considered FALSE:
...
the empty string, and the string "0"
...
Every other value is considered TRUE (including any resource).
In your case the $_POST['wants_sms'] variable contains a string "false";
My code is always returning true when I'm comparing these variables.
What am I doing wrong?
<?php
$postuser = (integer)bp_activity_user_id(); //echos 1int(0)
$posteduser = (integer)bp_activity_comment_user_id(); //echos 3int(0)
if ( $postuser === $posteduser) {
echo 'true';
} else {
echo 'false';
}
?>
You need to use the function that RETURNs the value, not outputs it.
From docs I found for whatever this is,
bp_activity_user_id() X-Ref
Output the activity user ID.
bp_get_activity_user_id() X-Ref
Return the activity user ID.
return: int The activity user ID.
The function you are using echoes the variable, NOT returns it and therefore you can't set a variable with that function. Same for the this function.
bp_activity_comment_user_id() X-Ref
Output the ID of the author of the activity comment currently being displayed.
bp_get_activity_comment_user_id() X-Ref
Return the ID of the author of the activity comment currently being displayed.
return: int|bool $user_id The user_id of the author of the displayed
To use in an assignment, the function has to return a value. That's why your values are always (int)0: the functions you are using have no return value. So, it returns null which is cast to 0.
<?php
$postuser = bp_get_activity_user_id();
$posteduser = bp_get_activity_comment_user_id();
//no need to cast: these functions return integers
if ( $postuser === $posteduser) {
echo 'true';
} else {
echo 'False';
Just use intval and == i think it should work and evaluate it fine
<?php
$postuser = intval(bp_activity_user_id()); //echos 1int(0)
$posteduser = intval(bp_activity_comment_user_id()); //echos 3int(0)
if ( $postuser == $posteduser) {
echo 'true';
} else {
echo 'False';
}
?>
Your prbolems are probably the wrong typecasts:
Change (integer) to (int)
$postuser = (int)bp_activity_user_id(); //echos 1int(0)
$posteduser = (int)bp_activity_comment_user_id();
http://php.net/manual/en/language.types.integer.php
How can I compare two variable strings, would it be like so:
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
And to check to see if a $_GET[] variable is present in the url would it be like this"
$myVars = $_GET['param'];
if ($myVars == NULL) {
//do code
}
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
$myVar = $_GET['param'];
if (isset($myVar)) {
//IF THE VARIABLE IS SET do code
}
if (!isset($myVar)) {
//IF THE VARIABLE IS NOT SET do code
}
For your reference, something that stomped me for days when first starting PHP:
$_GET["var1"] // these are set from the header location so www.site.com/?var1=something
$_POST["var1"] //these are sent by forms from other pages to the php page
For comparing strings I'd recommend using the triple equals operator over double equals.
// This evaluates to true (this can be a surprise if you really want 0)
if ("0" == false) {
// do stuff
}
// While this evaluates to false
if ("0" === false) {
// do stuff
}
For checking the $_GET variable I rather use array_key_exists, isset can return false if the key exists but the content is null
something like:
$_GET['param'] = null;
// This evaluates to false
if (isset($_GET['param'])) {
// do stuff
}
// While this evaluates to true
if (array_key_exits('param', $_GET)) {
// do stuff
}
When possible avoid doing assignments such as:
$myVar = $_GET['param'];
$_GET, is user dependant. So the expected key could be available or not. If the key is not available when you access it, a run-time notice will be triggered. This could fill your error log if notices are enabled, or spam your users in the worst case. Just do a simple array_key_exists to check $_GET before referencing the key on it.
if (array_key_exists('subject', $_GET) === true) {
$subject = $_GET['subject'];
} else {
// now you can report that the variable was not found
echo 'Please select a subject!';
// or simply set a default for it
$subject = 'unknown';
}
Sources:
http://ca.php.net/isset
http://ca.php.net/array_key_exists
http://php.net/manual/en/language.types.array.php
If you wanna check if a variable is set, use isset()
if (isset($_GET['param'])){
// your code
}
To compare a variable to a string, use this:
if ($myVar == 'hello') {
// do stuff
}
To see if a variable is set, use isset(), like this:
if (isset($_GET['param'])) {
// do stuff
}
All this information is listed on PHP's website under Operators
http://php.net/manual/en/language.operators.comparison.php
I'm using a variable in Javascript which will be set via Php e.g. var usesInterview = <?php echo 1;?>
If not, then var usesInterview = <?php echo 0;?>
How best should I handle this in my code? There will be a If statement to check for the variable and determine the route to take.
I've tried using typeof() == 1 and when I set it to 0, it still carries out the routine as if it where 1.
Why not set it with javascript:
usesInterview = 1;
Even if you set it with PHP, you can check like this:
if (usesInterview === 1){
// variable is equal to 1
}
else if (usesInterview === 0){
// variable is equal to 0
}
Notice the === to check for both type as well as value. If you don't want to check for type, you need to use == like this:
if (usesInterview == 1){
// variable is equal to 1 or "1" or true
}
else if (usesInterview == 0){
// variable is equal to 0 or "0" or "" or false
}
You should avoid the later approach when you are sure about both type as well as value.
More Information:
http://w3schools.com/JS/js_comparisons.asp
There are so many ways you can do it... Ie
var usesInterview = <?php echo [0|1];?>
usesInterview ? goingTrueWay() : goingFalsegWay();
or
<?php echo [0|1];?> ? goingTrueWay() : goingFalseWay();
or something like this:
var waysCollection = {
0: function () {...} //routine for usesInterview == 0
1: function () {...} //routine for usesInterview == 1
}
waysCollection[<?php echo [0|1];?>]();
also you can use one of the early suggestion:
if (<?php echo [0|1];?>) {
// truthy branch
} else {
// falsy branch
}
BTW, if you want usesInterview to be a boolean, yes/no trigger, - use true/false not 0/1. Its easier to read and understand later. For ex
var usesInterview = <?php echo [false|true];?>
if (usesInterview) {
//do this if `true`
} else {
//do this if `false`
}
typeof will return the type of the value - "number" in this case. You're using a non-strict equality check (==) so "number" == 1 is true.
Just check the value, using type-strict equality operator (===):
if (usesInterview === 1) {
// do something
}
else if (usesInterview === 0) {
// do something else
}
Read more about JavaScript comparison operators at https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators.
When usesInterview is 1 it's truthy. So it's as simple as:
if (usesInterview) {
// truthy branch
} else {
// falsy branch
}