Variable set to false - php

I wrote this REALLY simple code:
$foo=false;
echo $foo;//It outputs nothing
Why? Shouldn't it output false? What can I do to make that work?

false evaluates to an empty string when printing to the page.
Use
echo $foo ? "true" : "false";

The string "false" is not equal to false. When you convert false to a string, you get an empty string.
What you have is implicitly doing this: echo (string) $foo;

If you want to see a "true" or "false" string when you echo for tests etc you could always use a simple function like this:
// Boolean to string function
function booleanToString($bool){
if (is_bool($bool) === true) {
if($bool == true){
return "true";
} else {
return "false";
}
} else {
return NULL;
}
}
Then to use it:
// Setup some boolean variables
$Var_Bool_01 = true;
$Var_Bool_02 = false;
// Echo the results using the function
echo "Boolean 01 = " . booleanToString($Var_Bool_01) . "<br />"; // true
echo "Boolean 02 = " . booleanToString($Var_Bool_02) . "<br />"; // false

Related

Using php how to match boolean value with word in sentence?

I have a response from aws like this with boolean value :
$string=/vasff/fdsfsdf:boolean true
and $string=/sadasff/fdsfsdf:boolean false
in their documentation, they had written a response in boolean.// Success? (Boolean, not a CFResponse object).
Their documentaion is https://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.S3.S3Client.html#_doesObjectExist
how to match value is true or false? I tried this code but it always returns true.
if(stripos($string, true) !== false){
echo "true";
}
else{
echo "false";
}
EDIT
Just wanted to thank everyone for their good answers on this.
This code is working fine for aws s3 bucket response.
if($response == FALSE){
return false; }else{
return true;
}
if you mean by this :
$string=/vasff/fdsfsdf:boolean true
this :
$string='/vasff/fdsfsdf:boolean true';
you can use this code : use true with double quote
$string='/vasff/fdsfsdf:boolean true';
if(stripos($string, "true") !== false){
echo "true";
}
else{
echo "false";
}
Edit :
use your function paramaters intead of ....
if(doesObjectExist(....)){
echo "true";
}else{
echo "false";
}
You can try this:
preg_match_all("/:boolean (.+)/", $string, $mc);
if(isset($mc[1]) && isset($mc[1][0])){
if($mc[1][0] == "false"){
echo $mc[1][0] . " == false";
}
else{
echo $mc[1][0] . " == true";
}
}

Check if variable is true, false, set null if nothing

i am struggling with a rather simple task.
I am working with a REST backend, which sometimes receive a json-object as parameter like "api?params={"foo":bar}" . And "foo" can be true/false or null (undefined).
When i echo myParam(foo) when true, it echoes "true".
When foo is false, it returns nothing (i'd like it to echo "false"),
but when foo is not defined, when its not in the API-call, i want it to return "null".
I found a snippet on the net a long time a go, which i thought was working.
$foo = (null !== $jsonObj->foo ? $jsonObj->foo: "");
But its not working when foo is false or null.
$foo = var_export($jsonObj->foo, true);
This line however returns the variable as string, and returns it "correct", it returns "true" when true, "false" when false and "NULL" when null. And this i can work with .
switch ($foo) {
case "true":
$result = true;
break;
...
But, there must be a better way ? Right?
--- UPDATE ---
The solution that worked for me now was this:
(since im storing the value in an array, storing false will equal "")
$foo = is_null($jsonObj->foo) ? null : $jsonObj->foo;
This gave me foo = null if null/undefined, else true/false...
Then to store it in array, i used this:
$array["foo"] = (!is_null($foo) ? intval($foo) : null);
this stored it as 0/1 or "" if it was null, then i have 3 states i can work with.
But reading all your comments made me try for the best of solutions.
You could use php isset() function.
i.e. :
if (!isset($foo)) {
echo "foo is not set : ";
var_dump($foo);
echo "<br />";
}
// returns "foo is not set : NULL"
$foo = NULL;
if (!isset($foo)) {
echo "foo = NULL : ";
var_dump($foo);
echo "<br />";
}
// returns "foo = NULL : NULL"
$foo = false;
if (isset($foo)) {
echo "foo = false : ";
var_dump($foo);
echo "<br />";
}
// returns "foo = false : bool(false)"
$foo = true;
if (isset($foo)) {
echo "foo = true : ";
var_dump($foo);
}
// returns "foo = true : bool(true)"
Hope it helps.
I guess you are mixing up a string that contains "true" with a real boolean "true".
Use var_dump always to ensure the correct type of variables too.
var_dump($jsonObj->foo)
This will show you the exact type.
So if it is a string you have to check with something like (what you already to in the switch)
if($jsonObj->foo == "true")

How does PHP SimpleXML get evaluated as an expression?

Consider this PHP code:
<?php
$xmlString =
'<'.'?xml version="1.0" encoding="UTF-8"?'.'>' .
'<rootEl>' .
'<a attrA="valA">xxx</a>' .
'<b attrB="valB"/>' .
'<c>oink</c>' .
'<d/>'.
'<e>' .
'<f>zzz</f>' .
'</e>' .
'</rootEl>';
$xml = simplexml_load_string( $xmlString );
foreach ( $xml->children() as $child ) {
echo "\$CHILD [" . $child->getName() . "]: " . $child->asXML();
echo "\n";
$insideIf1 = false;
if ($child) { $insideIf1 = true; }
$insideIf2 = false;
if (true == $child) { $insideIf2 = true; }
$insideIf3 = false;
if ((boolean)$child) { $insideIf3 = true; }
echo " - if(\$CHILD) return \"true\"; else return \"false\"; : " . (($insideIf1)?"true":"false")."\n";
echo " - if(true == \$CHILD) return \"true\"; else return \"false\"; : " . (($insideIf2)?"true":"false")."\n";
echo " - if((boolean)\$CHILD) return \"true\"; else return \"false\"; : " . (($insideIf3)?"true":"false")."\n";
echo " - ((\$CHILD)?\"true\":\"false\"): " . (($child)?"true":"false")."\n";
echo " - ((true == \$CHILD)?\"true\":\"false\"): " . ((true == $child)?"true":"false")."\n";
echo " - (((boolean)\$CHILD)?\"true\":\"false\"): " . (((boolean)$child)?"true":"false")."\n";
echo "\n";
}
As per PHP documentation (online, see http://php.net/manual/en/control-structures.if.php):
As described in the section about expressions, expression is evaluated
to its Boolean value. If expression evaluates to TRUE, PHP will
execute statement, and if it evaluates to FALSE - it'll ignore it.
More information about what values evaluate to FALSE can be found in
the 'Converting to boolean' section.
The "converting to boolean" section of this explanation states:
Converting to boolean
When converting to boolean, the following values are considered FALSE:
...omissis...
SimpleXML objects created from empty tags
If you execute the code above, these are the results on my PHP 5.5.9-1ubuntu4.5 (cli):
$CHILD [a]: <a attrA="valA">xxx</a>
- if($CHILD) return "true"; else return "false"; : true
- if(true == $CHILD) return "true"; else return "false"; : true
- if((boolean)$CHILD) return "true"; else return "false"; : true
- (($CHILD)?"true":"false"): true
- ((true == $CHILD)?"true":"false"): true
- (((boolean)$CHILD)?"true":"false"): true
$CHILD [b]: <b attrB="valB"/>
- if($CHILD) return "true"; else return "false"; : true
- if(true == $CHILD) return "true"; else return "false"; : false
- if((boolean)$CHILD) return "true"; else return "false"; : true
- (($CHILD)?"true":"false"): true
- ((true == $CHILD)?"true":"false"): false
- (((boolean)$CHILD)?"true":"false"): true
$CHILD [c]: <c>oink</c>
- if($CHILD) return "true"; else return "false"; : false
- if(true == $CHILD) return "true"; else return "false"; : true
- if((boolean)$CHILD) return "true"; else return "false"; : false
- (($CHILD)?"true":"false"): false
- ((true == $CHILD)?"true":"false"): true
- (((boolean)$CHILD)?"true":"false"): false
$CHILD [d]: <d/>
- if($CHILD) return "true"; else return "false"; : false
- if(true == $CHILD) return "true"; else return "false"; : false
- if((boolean)$CHILD) return "true"; else return "false"; : false
- (($CHILD)?"true":"false"): false
- ((true == $CHILD)?"true":"false"): false
- (((boolean)$CHILD)?"true":"false"): false
$CHILD [e]: <e><f>zzz</f></e>
- if($CHILD) return "true"; else return "false"; : true
- if(true == $CHILD) return "true"; else return "false"; : false
- if((boolean)$CHILD) return "true"; else return "false"; : true
- (($CHILD)?"true":"false"): true
- ((true == $CHILD)?"true":"false"): false
- (((boolean)$CHILD)?"true":"false"): true
Children elements "b" and "d" ARE empty, therefore I was expecting "false", and "a", "c", "e" ARE NOT empty, so I was expecting "true".
As is comes out, that statement in PHP documentation is absolutely NOT true, and the behaviour doesn't even seem consistent: implicit or explicit casts to boolean don't behave the same way (see case of element "c"), and if the bare SimpleXML object is used as "if" conditional expression (both "if" and ternary operator), somehow that expression evaluates differently from a cast to boolean.
Does anyone have an idea of what's going on here?
First of all, let's discard some of your code.
foreach ( $xml->children() as $child ) {
echo "\$CHILD [" . htmlspecialchars($child->getName()) . "]: " . htmlspecialchars($child->asXML());
echo "\n";
$insideIf1 = false;
if ($child) { $insideIf1 = true; }
$insideIf2 = false;
if (true == $child) { $insideIf2 = true; }
$insideIf3 = false;
if ((boolean)$child) { $insideIf3 = true; }
var_dump($child);
// echo intval($child)."\n";
echo 'VALUE EVALUATES TO: '. $child."\n";
echo " - if(\$CHILD) return \"true\"; else return \"false\"; : " . (($insideIf1)?"true":"false")."\n";
echo " - if(true == \$CHILD) return \"true\"; else return \"false\"; : " . (($insideIf2)?"true":"false")."\n";
echo " - if((boolean)\$CHILD) return \"true\"; else return \"false\"; : " . (($insideIf3)?"true":"false")."\n";
// This part evaluated exactly same as above. So no need to make confusion
echo "\n";
}
Next:
First and third test
Those are basically same. Object is considered true, if it has properties. So basically xml tag without attributes has no properties (just var_dump them).
Objects without properties (does not have attributes BUT NOTE THEY CAN have value - which is returned by iterator) considered false: c, d
Second test
This test on the other hand does not test object itself. But all values returned by it from casting to: int, bool and string.
One of those tests calls for __toString magic method. Which returns value. Then it evaluates to true (Elements a and c)
So its not random, but has special rules while considering it true or false.
Forgot to add
Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.
This "strange" behaviour is result of it implementing inerators.
Edit:
As you stated in comment what made you analyze this behaviour. I think that you should never chose to check SimpleXML objects on if($obj) basis.
Instead, use SimpleXML::attributes() or strval to do all checks. Then you're sure what you're checking.
Edit2:
$xmlObject is considered true (is not empty) if it has Properties OR Chilren (subnodes) (that works fine)
To check if object has value you cast it to string.
In this case, empty does not mean if it has value, only if it has children or properties.

What should be passed into if() to print 'Hello World'?

What should be passed into the if() to print the output as "Hello World"? [Note: It should execute the else block.]
if(?){
} else {
echo "World";
}
I needs to evaluate to false, and print "Hello" at the same time. printf returns the length of outputted string upon success which is evaluated to true when read in a Boolean context. So reversing that will evaluate to false, executing the else block.
if(!printf("Hello ")){
} else {
echo "World";
}
!printf("Hello ")
By default, printf in 'C' returns true.
if(!printf("Hello "))
{}
else
{
echo "World";
}
You can do in this way...
There is also an alternate solution for this question:
class test{
function __construct()
{
echo "Hello";
}
}
if(!new test){
}else{
echo "World";
}
Anything that evaluates to FALSE.
if understands logical result, i mean TRUE-FALSE
so any any condition that results in true/false results matters for if so you can use
if(true){
echo 'this is executed';
}else{
echo "world";
}
OR
if(false){
echo 'this is executed';
}else{
echo "world";
}
i hope this works
if(printf("Hello ")) {
}
else{
echo "World";}
i think this is enough.....sorry if not

Check if page returns true or false

I am trying to verify a Minecraft username is paid or not.
By typing in the username at the end of the URL, it returns true or false.
$input = 'Notch';
function checkPlayer($player) {
$mcURL = 'http://www.minecraft.net/haspaid.jsp?user=';
$auth = file_get_contents($mcURL . $player);
if ($auth === true) {
echo $player. ' is valid';
} else {
echo $player. ' is not valid';
}
}
checkPlayer($input);
But it doesn't return true. By going to the page http://www.minecraft.net/haspaid.jsp?user=Notch, it does return true. How do I properly check? I think file_get_contents is the wrong function to use for this matter. I'm not sure though.
change this line :
if ($auth === true) {
with
if (trim($auth) == "true") {

Categories