This is an old revision of the document!
PHP RFC: In Operator
- Version: 0.3
- Date: 2015-02-20
- Authors: Niklas Keller me@kelunik.com, Bob Weinand bobwei9@hotmail.com
- Status: Draft
- First Published at: http://wiki.php.net/rfc/in_operator
Introduction
This RFC adds a new in
operator which simplifies contains
checks for strings and arrays. Currently, we have to use in_array($needle, $haystack, true)
or strpos($haystack, $needle) !== false
. These functions have a inconsistent parameter order, so it's hard to remember which is the right one for each. The in
operator makes these checks way more readable. Additionally, it also works for Traversable
.
Proposal
Add a new operator (expr1) in (expr2)
. It checks whether expr2
contains expr1
.
It uses strict comparison (===
) for array values / instances of Traversable
and doesn't search recursively.
$contains = "foo" in ["a", "b", "c"]; // false $contains = "foo" in ["foo", "bar"]; // true $contains = "foo" in [["foo"], ["bar"]]; // false $contains = "0e0" in ["0"]; // false, because of strict comparison $contains = 0 in ["0"]; // false, because of strict comparison
function gen () { yield "foo"; yield "bar"; } $contains = "bar" in gen();
If the first parameter is an array , it checks for every element whether it's contained in the $haystack
or not. This is an advantage compared to in_array
. It doesn't check the values in $needle
recursively, so it's still possible to check if an array contains another array, but makes checking multiple scalars easier:
$contains = ["foo", "bar"] in ["foo", "baz", "bar"]; // true $contains = ["foo", "bar", "baz"] in ["foo", "bar"]; // false $contains = [["foo", "bar"]] in [["foo", "bar"], ["foo", "baz"]]; // true $contains = [["foo", "bar"]] in ["foo", "bar"]; // false
For strings, it behaves exactly like strpos($haystack, $needle) !== false
:
$contains = "foo" in "foobar"; // true $contains = "php" in "foobar"; // false
Objects are not supported, because we already have isset
here.
Why strict?
It's strict because otherwise something like “foo” in [0]
would be true.
Precedence
It should have the same precedence as instanceof
, so it's possible to negate it:
if (!$input in $validValues) { // ... }
Backward Incompatible Changes
New reserved keyword in
. This affects function, class and method names.
Proposed PHP Version(s)
Next major release, at the time of writing PHP 7.
RFC Impact
New Constants
A T_IN
constant for use with ext/tokenizer has been added.
Open Issues
Make sure there are no open issues when the vote starts!
Future Scope
None.
Proposed Voting Choices
Requires a 2/3 majority, simple yes / no vote.
Patches and Tests
TBD
Implementation
TBD
Rejected Features
Keep this updated with features that were discussed on the mail lists.