My function is not called a second time why [duplicate] - php

The following code doesn't print out anything:
$bool_val = (bool)false;
echo $bool_val;
But the following code prints 1:
$bool_val = (bool)true;
echo $bool_val;
Is there a better way to print 0 or false when $bool_val is false than adding an if statement?

echo $bool_val ? 'true' : 'false';
Or if you only want output when it's false:
echo !$bool_val ? 'false' : '';

This is the easiest way to do this:
$text = var_export($bool_value,true);
echo $text;
or
var_export($bool_value)
If the second argument is not true, it will output the result directly.

This will print out boolean value as it is, instead of 1/0.
$bool = false;
echo json_encode($bool); //false

No, since the other option is modifying the Zend engine, and one would be hard-pressed to call that a "better way".
Edit:
If you really wanted to, you could use an array:
$boolarray = Array(false => 'false', true => 'true');
echo $boolarray[false];

Try converting your boolean to an integer?
echo (int)$bool_val;

I like this one to print that out
var_dump ($var);

var_export provides the desired functionality.
This will always print a value rather than printing nothing for null or false. var_export prints a PHP representation of the argument it's passed, the output could be copy/pasted back into PHP.
var_export(true); // true
var_export(false); // false
var_export(1); // 1
var_export(0); // 0
var_export(null); // NULL
var_export('true'); // 'true' <-- note the quotes
var_export('false'); // 'false'
If you want to print strings "true" or "false", you can cast to a boolean as below, but beware of the peculiarities:
var_export((bool) true); // true
var_export((bool) false); // false
var_export((bool) 1); // true
var_export((bool) 0); // false
var_export((bool) ''); // false
var_export((bool) 'true'); // true
var_export((bool) null); // false
// !! CAREFUL WITH CASTING !!
var_export((bool) 'false'); // true
var_export((bool) '0'); // false

echo(var_export($var));
When $var is boolean variable, true or false will be printed out.

This gives 0 or 1:
intval($bool_val);
PHP Manual: intval function

The %b option of sprintf() will convert a boolean to an integer:
echo sprintf("False will print as %b", false); //False will print as 0
echo sprintf("True will print as %b", true); //True will print as 1
If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b or %s for general string replacement.
Each pattern will be replaced by the argument in order:
echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");

You can use a ternary operator
echo false ? 'true' : 'false';

Your'e casting a boolean to boolean and expecting an integer to be displayed. It works for true but not false. Since you expect an integer:
echo (int)$bool_val;

json_encode will do it out-of-the-box, but it's not pretty (indented, etc):
echo json_encode(array('whatever' => TRUE, 'somethingelse' => FALSE));
...gives...
{"whatever":true,"somethingelse":false}

You can try this if you want debug an array:
function debug_array($a){
return array_map(function($v){
return is_bool($v) ? ($v ? 'true' : 'false') : $v;
}, $a);
}
To use it:
$arr = debug_array(['test' => true, 'id' => false]);
print_r($arr); // output Array ( [test] => true [id] => false )

Related

getting wrong or nothing for password_verify return value [duplicate]

The following code doesn't print out anything:
$bool_val = (bool)false;
echo $bool_val;
But the following code prints 1:
$bool_val = (bool)true;
echo $bool_val;
Is there a better way to print 0 or false when $bool_val is false than adding an if statement?
echo $bool_val ? 'true' : 'false';
Or if you only want output when it's false:
echo !$bool_val ? 'false' : '';
This is the easiest way to do this:
$text = var_export($bool_value,true);
echo $text;
or
var_export($bool_value)
If the second argument is not true, it will output the result directly.
This will print out boolean value as it is, instead of 1/0.
$bool = false;
echo json_encode($bool); //false
No, since the other option is modifying the Zend engine, and one would be hard-pressed to call that a "better way".
Edit:
If you really wanted to, you could use an array:
$boolarray = Array(false => 'false', true => 'true');
echo $boolarray[false];
Try converting your boolean to an integer?
echo (int)$bool_val;
I like this one to print that out
var_dump ($var);
var_export provides the desired functionality.
This will always print a value rather than printing nothing for null or false. var_export prints a PHP representation of the argument it's passed, the output could be copy/pasted back into PHP.
var_export(true); // true
var_export(false); // false
var_export(1); // 1
var_export(0); // 0
var_export(null); // NULL
var_export('true'); // 'true' <-- note the quotes
var_export('false'); // 'false'
If you want to print strings "true" or "false", you can cast to a boolean as below, but beware of the peculiarities:
var_export((bool) true); // true
var_export((bool) false); // false
var_export((bool) 1); // true
var_export((bool) 0); // false
var_export((bool) ''); // false
var_export((bool) 'true'); // true
var_export((bool) null); // false
// !! CAREFUL WITH CASTING !!
var_export((bool) 'false'); // true
var_export((bool) '0'); // false
echo(var_export($var));
When $var is boolean variable, true or false will be printed out.
This gives 0 or 1:
intval($bool_val);
PHP Manual: intval function
The %b option of sprintf() will convert a boolean to an integer:
echo sprintf("False will print as %b", false); //False will print as 0
echo sprintf("True will print as %b", true); //True will print as 1
If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b or %s for general string replacement.
Each pattern will be replaced by the argument in order:
echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");
You can use a ternary operator
echo false ? 'true' : 'false';
Your'e casting a boolean to boolean and expecting an integer to be displayed. It works for true but not false. Since you expect an integer:
echo (int)$bool_val;
json_encode will do it out-of-the-box, but it's not pretty (indented, etc):
echo json_encode(array('whatever' => TRUE, 'somethingelse' => FALSE));
...gives...
{"whatever":true,"somethingelse":false}
You can try this if you want debug an array:
function debug_array($a){
return array_map(function($v){
return is_bool($v) ? ($v ? 'true' : 'false') : $v;
}, $a);
}
To use it:
$arr = debug_array(['test' => true, 'id' => false]);
print_r($arr); // output Array ( [test] => true [id] => false )

Why does "echo !!!0" output as 1?

i couldn't understand why i am getting the output "1" from the below statement in PHP,
<?php echo !!!0;?>
please let me know the reason
The statement is parsed as !(!(!0)). ! is the logical negation operator. When applying it to any other type than a boolean (true/false), the operand is first cast to a boolean value (0, empty string, empty array, null, empty SimpleXML objects = false; everything else true).
Let's break the statement down:
!!!0 ==
!!!false ==
!!true ==
!false ==
true
Finally, echo true will output 1.
Because PHP "casts" the 0 to a boolean when doing a logic operation.
So !0 is 1
!1 is 0
!0 is 1
! is used to negate statements (post-evaluated).
0 evaluates to false => true (1) => false (0) => true (1)
! ! !
Why is a number cast to boolean?
This happens implicitly by using !, the exclamation mark expects yes true or no false and so the value next to it gets automatically cast to something that fits this condition (yes or no).
You can make similiar experiments using:
var_dump( !"hello world" );
// ...
Explicit casts are done by putting the type in brackets: (boolean)1 === true
Update for #user2864740:
<?php
var_dump(!0 === true); // bool(true)
var_dump(!(0) === true); // bool(true)
var_dump((!0) === true); // bool(true)
var_dump((boolean)1 === true); // bool(true)
var_dump((boolean)1); // bool(true)
Update after discussion:
echo true; prints 1. But this does not change a variable for example:
$x = true;
echo $x; // 1
var_dump($x); // bool(true)

PHP in_array issue while checking zero value in array giving true

I am facing one strange situation while working with PHP's in_array(). Below is my code and its output
<?php
$process = array("as12"=>"deleted","as13"=>1,"as14"=>1);
if(!in_array(0, $process))
echo "success";
else
echo "not success";
//It's outputting "not success";
var_dump(in_array(0, $process));
//Output : null
var_dump(in_array(0, $this->tProcessActions) === true);
///Output : true
If we look at the $process array, there is no 0 value in it. Still it's giving me true if I check if(in_array(0, $process))
Can anybody has idea about it?
If you need strict checks, use the $strict option:
in_array(0, $process, true)
PHP's string ⟷ int comparison is well known to be complicated if you don't know the rules/expect the wrong thing.
Try like
if(!in_array('0', $process)) {
or you can use search(optional) like
if(array_search('0',$process)) {
I believe you should put 0 inside the quotes:
if(!in_array("0", $process))
I think because in_array maybe not strict type check. because if you check
if (0 == "deleted") echo "xx";
Try this
if(!in_array('0', $process))
using the strict parameter gives what you want here:
$process = array("as12"=>"deleted","as13"=>1,"as14"=>1);
var_dump( in_array(0, $process, true ) );
// gives false
or use array_search and test if non-false;
var key = array_search( 0, array( 'foo' => 1, 'bar' => 0 ) );
// key is "bar"
You need use third parameter [$is_strict] of in_array function.
in_array(0, $process, true)
The point is what any string after (int) conversion equal to 0.
(int) "deleted" => 0.
So in_array without strict mode is equal to "deleted" == 0 which true. When you use strict its equal to "deleted" === 0 which false.

PHP Count Number of True Values in a Boolean Array

I have an associative array in which I need to count the number of boolean true values within.
The end result is to create an if statement in which would return true when only one true value exists within the array. It would need to return false if there are more then one true values within the array, or if there are no true values within the array.
I know the best route would be to use count and in_array in some form. I'm not sure this would work, just off the top of my head but even if it does, is this the best way?
$array(a->true,b->false,c->true)
if (count(in_array(true,$array,true)) == 1)
{
return true
}
else
{
return false
}
I would use array_filter.
$array = array(true, true, false, false);
echo count(array_filter($array));
//outputs: 2
Array_filter will remove values that are false-y (value == false). Then just get a count. If you need to filter based on some special value, like if you are looking for a specific value, array_filter accepts an optional second parameter that is a function you can define to return whether a value is true (not filtered) or false (filtered out).
Since TRUE is casted to 1 and FALSE is casted to 0. You can also use array_sum
$array = array('a'=>true,'b'=>false,'c'=>true);
if(array_sum($array) == 1) {
//one and only one true in the array
}
From the doc : "FALSE will yield 0 (zero), and TRUE will yield 1 (one)."
Try this approach :
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Result :
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
Documentation
like this?
$trues = 0;
foreach((array)$array as $arr) {
$trues += ($arr ? 1 : 0);
}
return ($trues==1);
Have you tried using array_count_values to get an array with everything counted? Then check how many true's there are?

Can boolean needle be passed to in_array?

Can I pass false as a needle to in_array()?
if(in_array(false,$haystack_array)){
return '!';
}else{
return 'C';
}
The $haystack_array will contain only boolean values. The haystack represents the results of multiple write queries. I'm trying to find out if any of them returned false, and therefore not completed.
PHP won't care what you pass in as your 'needle', but you should probably also use the third (optional) parameter for in_array to make it a 'strict' comparison. 'false' in PHP will test as equal to 0, '', "", null, etc...
Yep, just like in your example code. Because in_array returns a boolean to indicate whether the search was successful (rather than returning the match), it won't cause any problems.
There's got to be a better way.
<?php
echo (in_array(false,array(true,true,true,false)) ? '!' : 'C');
echo (in_array(false,array(true,true,true,true)) ? '!' : 'C');
Output:
!C
Yes you can but why don't you do it with a single boolean variable like this:
$anyFalseResults = false;
... your query loop {
// do the query
if( $queryResult == false ) $anyFalseResults = true;
}
at the end of the loop $anyFalseResults will contain what you are looking for.

Categories