3 ms·
PHP does this (with a warning). I'm not sure if this should be an argument for or against. <?php $foo = array(); echo $foo['a']['b']['c']; // not a
by MatmaRex 11y ago
PHP does this (with a warning). I'm not sure if this should be an argument for or against.
<?php
$foo = array();
echo $foo['a']['b']['c']; // not an error
- vidarh 11y agoHere's a slightly evil way of handling this specific case in Ruby: d = lambda {|hash,key| Hash.new(&d) } foo = Hash.new(&d) p foo['a']['b']['c'] The argument to "Hash.new" is the default value, or a on object that takes the hash object itself and the key, and returns the default value (and optionally stores it in the hash, which makes it great for memoization). In this case, whenever accessing a non-existent hash key, it returns another hash with the same closure as the default... Of course it's likely to blow up in all kinds of ways since anything trying to do "if foo['a']" to check of 'a' is present in foo will break, for example.
- juriansluiman 11y agoThat's where the coalesce operator ("??") is for. Exactly to suppress the warning and avoid verbose isset() calls: echo $foo['a']['b'] ?? 'default_value';
- Udo 11y agoI'm looking forward to this in PHP7. My current workaround, which exists for the same reason as the coalesce operator (https://wiki.php.net/rfc/isset_ternary https://wiki.php.net/rfc/isset_ternary) is a custom function: $v = @first($var1, $var2, 'some-default'); which will simply return the first parameter that has a non-null, non-empty-string value.