Boolean input flipping - php

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

Related

How to treat zero values as true using php?

Here is my sample code:
$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
echo 'true';
}
else{
echo 'false';
}
If I pass 0 to $_POST['issue_id'] by form submitting then it echo false. Which I want is: Condition will be true if the following conditions are fulfilled:
1. true when I pass any value having 0.
2. false when I don't pass any value. i.e: $_POST['issue_id'] is undefined.
I also tried this:
if(!isset($issue_id)){
echo 'true';
}
else{
echo 'false';
}
if(!empty($issue_id) || $issue==0){
echo 'true';
}
else{
echo 'false';
}
The last one is okay, meaning if I pass any value having ZERO then it will echo true. But it will also echo true if I don't pass any value. Any idea?
The last is okay, meaning if I pass any value having ZERO then it echo true. But it also echo true if I don't pass any value. Any idea?
if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}
please notice I used !== not !=. this is why:
0 == "" // true
0 === "" // false
See more at http://php.net/manual/en/language.operators.comparison.php
also if you are expecting number you can use
if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}
since is_numeric("") returns false
http://php.net/manual/en/function.is-numeric.php
Alternatively if you expect number good option is filter_var
if (isset($_POST["issue_id"]) {
$issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
if ($issue_id !== false) {
}
}
since filter_var("", FILTER_VALIDATE_INT) will returns false and filter_var("0", FILTER_VALIDATE_INT) will return (int) 0
http://php.net/manual/en/function.filter-var.php
if(isset($_POST['issue_id'])) {
if($_POST['issue_id'] == 0) {
echo "true";
}
else {
echo "false";
}
}
When you get data from a form, remember:
All text boxes, whether input or textarea will come as strings. That includes empty text boxes, and text boxes which contain numbers.
All selected buttons will have a value, but buttons which are not selected will not be present at all. This includes radio buttons, check boxes and actual buttons.
This means that $_POST['issue_id'] will be the string '0', which is actually truthy.
If you need it to be an integer, use something like: $issue_id=intval($_POST['issue_id']);
#Abdus Sattar Bhuiyan you can also full fill your two condition like below one:
<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0") ? true : false : false;
if($issue_id){
echo 'true';
}
else{
echo 'false';
}

PHP Statement always return false

I have a little script witch fetches data from IMDB with omdbapi.
I've managed to get the data from the site, but when I try to check if the movie's poster is valid, it always returns false.
if(!$info['Poster'] == "N/A") {
$url = $info['Poster'];
$img = 'images/'.$info["imdbID"].'.jpg';
file_put_contents($img, file_get_contents($url));
echo 'Downloaded';
} else {
echo '!Downloaded';
$noCover = true;
}
The $info['Poster'] is containing data similar to this:
http://ia.media-imdb.com/images/M/MV5BMTM0MDgwNjMyMl5BMl5BanBnXkFtZTcwNTg3NzAzMw##._V1_SX300.jpg
It was working a while ago, but it somehow stopped...
Your if statement is written incorrectly. !$info['Poster'] means if $info['Poster'] is not true. If there is a value it will be translated to false as PHP's type juggling converts any non-empty string to true and the ! operator makes that false. false does not equal N/A as type juggling converts that to true (non-empty strings are always true). false is not equal to `true.
You mean to use != which means not equal to
if($info['Poster'] != "N/A") {
Just move the ! from your condition, And it should work as expected. You are asking in your condition if $info['Poster'] is false, and it wont be false because it will have a string value. So, you are comparing a boolean value with a string value, false will be always different to "N/A:
if($info['Poster'] !== "N/A") {
$url = $info['Poster'];
$img = 'images/'.$info["imdbID"].'.jpg';
file_put_contents($img, file_get_contents($url));
echo 'Downloaded';
} else {
echo '!Downloaded';
$noCover = true;
}

use html localStorage in PHP

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 ===. :)

How could a PHP value contain a string of zero length not equal to the empty string or null?

I am retrieving some data from an in-house store and in case of failure, I get a very specific response. Calling strlen() on this variable returns the value of zero. It is also not equal to NULL or "". I'm using this code to test:
if ($data === NULL)
{
echo("data was null\n");
}
else if ($data === "")
{
echo("data was empty string\n");
}
else if (strlen($data) == 0)
{
echo("data was length zero\n");
}
This result is outputting data was length zero. What could the variable contain that is zero length, not null, and not the empty string?
Returned value must be false then.
echo strlen(false); // outputs 0
This may not being an answer. I can only answer if you present a var_dump($data); But I think also suprising for me is this:
$data = "\0";
if ($data === NULL)
{
echo("data was null\n");
}
else if ($data === "")
{
echo "data was empty string\n";
}
else if (strlen($data) == 0)
{
echo "data was length zero\n";
}
else
{
echo "something strange happened\n";
}
Output: something strange happened
:)
Try this :
$data = false;
I'm not sure why false has a strlen, but it does.

can php return a boolean? => return $aantal == 0;

can php return a boolean like this:
return $aantal == 0;
like in java you can
public boolean test(int i)
{
return i==0;
}
or do you Have to use a if contruction?
because if i do this.
$foutLoos = checkFoutloos($aantal);
function checkFoutloos($aantal)
{
return $aantal == 0;
}
echo "foutLoos = $foutLoos";
it echo's
foutLoos =
so not true or false
thanks
matthy
It returns a boolean, but the boolean is not converted to a string when you output it. Try this instead:
$foutLoos = checkFoutloos($aantal);
function checkFoutloos($aantal)
{
return $aantal == 0;
}
echo "foutLoos = " . ( $foutLoos ? "true" : "false" );
Try it out!
function is_zero($n) {
return $n == 0;
}
echo gettype(is_zero(0));
The output:
boolean
yes ideed i found out that when you echo a false you get nothing and true echo's 1 thats why i was confused ;)
Yes. you can even through in the ternary operator.
function foo($bar == 0) {
return ($bar) ? true : false;
}
Yes, you can return a boolean test in the return function. I like to put mine in parenthesis so I know what is being evaluated.
function Foo($Bar= 0) {
return ($Bar == 0);
}
$Return = Foo(2);
$Type = var_export($Return, true);
echo "Return Type: ".$Type; // Return Type: boolean(true)
In fact, almost anything can be evaluated on the return line. Don't go crazy though, as it may make refactoring more difficult (if you want to allow plugins to manipulate the return, for instance).
You could just do it like this i think, with type casting:
return (bool) $aantal;

Categories