Hello Niklas, On Sun, Jan 18, 2015 at 6:42 PM, Niklas Keller <m...@kelunik.com> wrote:
> Hello, > > I'd like to propose a new feature to PHP: The in Operator > Bob mentioned a few weeks ago he wants such an operator in PHP and today I > stumbled over > > http://nikic.github.io/2012/07/27/How-to-add-new-syntactic-features-to-PHP.html > again, > which uses the in operator as a sample. > I am very familiar with the in operator. However, the implementation would be incomplete without handling loops via the in operator. Many people when seeing an in operator also think of JavaScript. In that case the in operator iterates over properties. As such in PHP we should be able to iterate over associative arrays should the syntax be added. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in > Use cases: > > $obj = new StdClass; > $obj->prop = "value"; > $languages = ["PHP", "C", "Java"]; > var_dump("PHP" in $languages); // true > var_dump("Python" in $languages); // false > var_dump(0 in $languages); // false > var_dump("0x0" in ["0e3"]); // false > var_dump("prop" in $obj); // true > var_dump("foo" in $obj); // false > var_dump("Hello" in "Hello World!"); // true > > For strings, it would replace `strpos("Hello World!", "Hello") !== false)`, > for arrays it would replace `in_array($needle, $haystack, true)` > and for objects it would be a replacement of property_exists($class, > $property)`. > > This change would mainly be syntax sugar, but I think it's worth because: > * `"0x0" in ["0e3"]` would return false while `in_array("0x0", ["0e3"])` > returns true, that's probably an edge case, but there may be a lot of > people that don't use the `$strict` parameter, see http://3v4l.org/0K7E5 > * It would solve the issue that it's hard to remember the order of the > arguments for in_array and strpos, just had to look it up again. > I do think that it would be nice for a few different reasons but the in operator as such can also cause a bit of confusion and misdirection depending on how it is implemented. In the use cases above you do mention some inconsistencies with PHP functions that already exist. Additionally you did mention objects, in what scope would it properly leverage? My assumption would be visible properties from the context which you are in. Regards, Mike