PHP in_array function give annoying result [duplicate] - php

This question already has answers here:
Comparing String to Integer gives strange results
(5 answers)
Closed 2 years ago.
PHP 7
in_array('one', [0 => 0]) //true
in_array('one', [0]) //true
in_array('one', array_keys([0 => 0])); //true
Expected result is FALSE, because obviously there are no string values in given array, also there are no 'true' values (string can be evaluated to true and match)
If we assume any type comparsion 0 integer is always compared to false in PHP, and String compared to true, so why this works anyway?
I know, strict mode exists and works fine, but anyway absolute annoying why this happend. Any explanation?

The answer to your question is here:
Comparing String to Integer gives strange results
Same situation when "one" == 0 as in your examples.
TL:DR - on string-to-integer comparison the string will be converted to integer, not the integer to string, so "one" will be converted to 0

in_array works when u use it like this
in_array('one', [0,1])

in_array function expect array as indexed array i.e [0,1,"two"] not associative array (Key value pair).
You can use array_values to ignore the key of specific, it returns only values.
in_array('one', array_values([0 => 0])) // true //tested

Related

whats the difference between $a = (true === !!array_intersect(['1'],[3,2,1])); and checking with in_array

When to use this:-
$a = (true === !!array_intersect(['1'], [3, 2, 1]));
and when to use this
$b = in_array('1', [3,2,1]);
Both returns same.
array_intersect() returns the common elements form both array. In your code array_intersect(['1'], [3,2,1]) the returns [1] and when use !! then it's value is true. Because:
![1] is false
Again !false gets true
Finally (true === !!array_intersect(['1'], [3,2,1])) return true, because both sites are true. Note: === is used to check strictly (with type). That means the value of $a is true.
Second part of code:
in_array() is used to check weather an element is exist or not in an array. In your code in_array('1',[3,2,1]); is true because 1 is exist in array [3, 2, 1]
The difference between array_intersect() and in_array() are:
array_intersect($arr1, $arr2) return an array which are common in both array $arr1 and $arr2
in_array($elm, $arr) returns a Boolean (true or false) based on the existence of $elm in the array $arr
Since both parts of your code are getting logically true, that's why you are getting the same value true.
in_array is much more readable compared to the array_intersect version of the same. However, array_intersect is much faster compared to in_array. So to answer your question, use array_intersect only if you are dealing with a data set large enough to raise performance issues. Otherwise sticking to in_array will make life easier for the next developer. Cheers
Both are different things.
array_intersect Compare the values of two arrays, and return the matches:
$a1=array(0=>"red",1=>"green",2=>"blue",3=>"yellow");
$a2=array(0=>"red",1=>"green",2=>"blue");
$result=array_intersect($a1,$a2);
print_r($result);
Output will be
Array ( [0] => red [1] => green [2] => blue )
in_array is for check if the value exists or not.
$a1=array(0=>"red",1=>"green",2=>"blue",3=>"yellow");
in_array('red',$a); //true
in_array('black',$a); //false
Now, If you want to check the value is exists in an array then you may use in_array it'll return true or false, Or if you want get matches value from two array then you may use array_intersect.
It's not quite the same though. From the docs:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
So, when using array_intersect(), you will always get true, but only because the string representation of your second array element "1" matches that of the array you intersect it with. With in_array(), you can have a third argument, strict, which is a boolean to indicate whether to also use type checking (see here). So, in your second example, you also have the option of checking whether the type matches, which is more fine-grained.
Personally, I would use the second option in any case just for its readability.
If you want to find elements in an array and get a subarray, then you should go for array_intersect() for performance reasons see accepted answer to this post

Comparing PHP arrays with integers, what is the real behavior

Today I faced a weird behavior on PHP (v: 7.1) arrays.
$emptyArray = [];
echo empty($emptyArray);
echo count($emptyArray);
echo (($emptyArray > 0));
The first two echos results is known (empty : true , count: 0), but the last one which confused me returned true!
Why PHP considered an empty array is larger than zero ?!
The answer is to be found in the rules for comparisons between different types:
Operand 1 Operand 2 Result
... ... ...
array anything array is always greater
Why PHP considered an empty array is larger than zero ?!
It is written in the documentation: when it is compared with an object of a different type, the array is always greater.

in_array function returns true when passing empty array

I noticed the following strange occurrence:
var_dump(in_array("test", array_keys(array("hello"))));
Yields: bool(true)
How is this possible? Array does not contains keys, therefore array_keys() will return an empty array. Test is not in this empty array, so why would it return true? Is this a bug in PHP?
simple answer: loose typing, 'test' == 0
Use
var_dump(in_array("test", array_keys(array("hello")), true));
for strict typing
And all arrays have keys, if you don't explicitly assign a key, then PHP will assign one based on incrementing integers from 0 (hence 'test' == 0).... array_keys() will not be empty, because PHP will assign a key of 0 to your array entry of "hello"

php casting variable to array

I am dealing with very strange issue of dealing with garbage in iterating through variable which has been cast to an array
$arr = (array)$var; // problem
$arr = array($var); // ok
The first method seems to work fine on values with integers, but not with strings. Is there any documented difference and does php have real casting ?
The problem is with lavarel 4, Database sources, function on line 704
If $var is a scalar, it's documented that both lines do the same:
For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).
http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
There are two ways to cast a variable in PHP as a specific type.
using the settype() function
using (int) (bool) (float) etc
More Info : http://www.electrictoolbox.com/type-casting-php/

want my if($object) to evaluate false when count($object) === 0 [duplicate]

This question already has answers here:
Evaluate object to a boolean
(6 answers)
Closed 9 years ago.
I made an object that was suposed to represent an array, but with a few methods. So I made it implement the native interfaces: IteratorAggregate and Countable. That way you can foreach and count it. So far so good.
But now I want it to evaluate like an array as well. So, if count($object) is zero, if($object) is suposed to evaluate as false. Is there a Comparable interface or something?
Use type Juggling.
You can assign the expected type of your var.
$object = count ( $object );
$object = (array) $object;
The same way, if you want to assign to your variable some other type, here is list of possible values:
(int)
(bool)
(float)
(string)
(array)
(object)
(unset)
(binary)
Also check this this Comparable interface.
The documentation shows everything that evaluates to false:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
As of this list an object will never be considered as false. So the only way is to cast the value of count() to boolean using (bool) if you need to do a strict comparison as pointed out in Tomi Sebastián Juárez's answer.

Categories