Short and safe array iteration One reason to follow development mailing lists is you sometimes pick up on some very neat tricks. Here's one that I spotted on the PHP Internals list recently to simplify array iteration in PHP 7. PHP's largely loose, dynamic typing has plenty of both pros and cons. One con in particular is that you don't always know for sure if a value you're trying to use has been set yet, or is non-null. PHP will dutifully whine at you if you try to use a null value, sometimes fatally. (Yet another reason to structure your code to avoid nulls, period.) One place this comes up in particular is in foreach() loops, especially when working with nested array structures. (PHP lacks a struct type, but makes anonymous hash maps so easy that they get used as the uber data type, for better or worse.) Consider the following: <?php foreach ( $definition [ 'keys' ] as $id => $val ) { // ... } ?> This not-at-all uncommo...
Comments
Post a Comment