Hello :-),

Thank you for the proposal. I have a question though: How is it different from:

* `foreach ($foo ?: [] as $bar) { … }` if `$foo` does not exist,

* `foreach ((array) $foo as $bar) { … }` if `$foo` is not an array.

I understand your issue, but you can probably type your data with `iterable`, `Generator`, `array`, `Iterator`…

Also, I am not sure that `??$x` really means `if (is_array($x)) { … }`.


Regards.


On 11.07.17 17:02, Mark Shust wrote:
Hello,

I wanted to garnish feedback on a RFC proposal. This is just a concept at
this point, and is inspired by the null coalesce operator.

Code will error if a non-array value is passed through a looping feature.
For example, this code:

<?php

$foo = "abc";

foreach ($foo as $bar) {

   echo $bar;

}


will result in the error:

PHP Warning:  Invalid argument supplied for foreach() in test.php on line 3


To prevent this, the logical solution is to wrap this in an is_array check:

<?php

$foo = "abc";

if (is_array($foo)) {

   foreach ($foo as $bar) {

     echo $bar;

   }

}


This code runs successfully and does not error out. For a syntactic
sugar/improvement, this can be shorthand for executing the loop instead of
wrapping the block within an is_array check:


<?php

$foo = "abc";

foreach (??$foo as $bar) {

   echo $bar;

}


Let me know your thoughts.


Cheers,
Mark



--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to