PHP in_array issue while checking zero value in array giving true - php

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.

Related

My function is not called a second time why [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 )

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 )

PHP - What is the difference between '!== false' and ' == true'?

Sometimes I see people write conditional statements like this:
if($var !== false) {...}
Instead of like this:
if($var == true) {...}
These are the same, right?
I see the former used much more frequently and am wondering if there is a reason behind this, or if it is just personal preference.
I appreciate that this might be opinion based, but I am curious to see if there is a legitimate reason behind this.
This:
if($var !== false) {...}
will only evaluate to false if $var is exactly false. It will not evaluate to false if $var is any other value, whether 'false-y' or not.
This:
if($var == true) {...}
will evaluate to false for any 'false-y' value. e.g. 0, '0'.
In addition this:
if($var === true) {...}
will evaluate to true only if $var is exactly set to true, not other 'truthy-y' values.
So you are correct that they are the same if you know $var is exclusively one of either true or false, but they behave differently for other values.
$var !== false could be used for something other than readability or personal preference. Various PHP functions are expected to return false in case of error and they might as well return a falsy value on success. Take strpos for example:
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
This means the function can return an integer, even 0 if the needle was found at the beginning, and false if needle was not found. You have to use !== false to check if the expression is false, not falsy.
They're not the same.
!== is a strict comparison that compares value and type. $var has to equal (bool) false. This means if a string of 'false' was returned it would fail.
== is a loose comparison that just checks the value. This means $var can equal '(string) string' and be true. When checking a var like this:
if ($var == true) {
}
you check if $var has anything in it/defined. As long as something is a against it (and doesn't equal (bool) false) it will pass the conditional. This means '(string) false' would pass that conditional.
Worth nothing some functions (like strpos) return (bool) false so doing the first one (IMO) is better for those sort of functions.
When you use ==
First, it typecast the variable and compare are those values same.
You can see in the following example
var_dump(0==FALSE); // ( 0 == ( int ) false ) bool(true)
var_dump(0=='anystring'); // ( 0 == ( int ) 'anystring' ) bool(true)
When you use ===
It compares the value and types too
So it would be something like
var_dump( gettype( 0 ) == gettype( false ) && 0 == false )
This is faster in case if your type check fails Since it has not to typecast the value for further 'value check' if type check fails.

PHP's variable type leniency

The most recent comment on PHP's in_array() help page (http://uk.php.net/manual/en/function.in-array.php#106319) states that some unusual results occur as a result of PHP's 'leniency on variable types', but gives no explanation as to why these results occur. In particular, I don't follow why these happen:
// Example array
$array = array(
'egg' => true,
'cheese' => false,
'hair' => 765,
'goblins' => null,
'ogres' => 'no ogres allowed in this array'
);
// Loose checking (this is the default, i.e. 3rd argument is false), return values are in comments
in_array(763, $array); // true
in_array('hhh', $array); // true
Or why the poster thought the following was strange behaviour
in_array('egg', $array); // true
in_array(array(), $array); // true
(surely 'egg' does occur in the array, and PHP doesn't care whether it's a key or value, and there is an array, and PHP doesn't care if it's empty or not?)
Can anyone give any pointers?
763 == true because true equals anything not 0, NULL or '', same thing for array because it is a value (not an object).
To circumvent this problem you should pass the third argument as TRUE to be STRICT and thus, is_rray will do a === which is a type equality so then
763 !== true
and neither will array() !== true
Internally, you can think of the basic in_array() call working like this:
function in_array($needle, $haystack, $strict = FALSE) {
foreach ($haystack as $key => $value) {
if ($strict === FALSE) {
if ($value == $needle) {
return($key);
}
} else {
if ($value === $needle) {
return($key);
}
}
return(FALSE);
}
note that it's using the == comparison operator - this one allows typecasting. So if your array contains a simple boolean TRUE value, then essentially EVERYTHING your search for with in_array will be found, and almost everything EXCEPT the following in PHP can be typecast as true:
'' == TRUE // false
0 == TRUE // false
FALSE == TRUE // false
array() == TRUE // false
'0' == TRUE // false
but:
'a' == TRUE // true
1 == TRUE // true
'1' == TRUE // true
3.1415926 = TRUE // true
etc...
This is why in_array has the optional 3rd parameter to force a strict comparison. It simply makes in_array do a === strict comparison, instead of ==.
Which means that
'a' === TRUE // FALSE
PHP treating arrays as primitive values is a constant source of pain as they can be very complex data structures, it doesn't make any sense. For example, if you assign array to something, and then modify the array, the original isn't modified, instead it is copied.
<?php
$arr = array(
"key" => NULL
);
var_dump( array() == NULL ); //True :(
var_dump( in_array( array(), $arr ) ); //True, wtf? It's because apparently array() == NULL
var_dump( in_array( new stdClass, $arr ) ); //False, thank god
?>
Also, 'egg' is not a value in the array, it's a key, so of course it's surprising that it would return true. This kind of behavior is not ok in any other language I know about, so it will trip over many people who don't know php quirks inside out.
Even a simple rule that an empty string is falsy, is violated in php:
if( "0" ) {
echo "hello"; //not executed
}
"0" is a non-empty string by any conceivable definition, yet it is a falsy value.

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