I use PHP’s in_array() function.
The following PHP code example:
<?php
$basket = [ 'apple', 'pear', 'banana' ];
if (!in_array('raspberry', $basket)) {
$basket[] = 'raspberry';
}
var_dump($basket);
Do you suggest to specify the strict = true
parameter?
I think it is not necessary because it is ensured that there are only strings in the array (no null, nor something of other type).
Also the 1st argument of the function is ensured to be a string.
Because I am unsure and would like to know if it is correct to specify strict = true
only for cases when there objects in the array of various types and the argument might be of a different type.
Looking forward to hear more from the community here.
2
Answers
You are mostly correct in your logic about the
strict
parameters. For one, I rarely use it because I rarely deal with mixed arrays in my actual codebase and when I have to deal with mixed array, I prefer to convert them to a particular type before doing comparison.As per the documentation of
in_array
on php.net, here is the definition of thestrict
parameter:According to this definition and your use case, you do not need to pass
strict=true
for the comparison to work correctly.For the case you outline in the question, no, but only because I would not even suggest to use
in_array()
there at all (and theif
etc.), but just:But not without confirming your writing with a "strictly speaking, yes":
Yes, this is correct, especially when all values have the same type and there is no difference between weak (
==
) and strict (===
) comparison for that type (hint: this can differ per type, e.g. object, array and it is true in your example with the string type).Therefore, the rule of thumb is to specify it as
true
like always, when you want or mean strict comparison. This is so that your code communicates better. And vice-versa forfalse
.In your example, you won’t need to verify the types of the first parameters to find out whether or not strict comparison is in effect, for example, if you would have used $strict = true. You just see it, because it is written in the third parameter.
When not specifying it and revisiting the code later, it is not clear any longer what was intended by the original author. So it makes the code easier to maintain when you specify the third parameter, regardless of true or false.
https://php.net/in_array