Web lists-archives.com

[PHP] Re: A 'missing' PHP primitive?




On 09.11.2016 at 16:02, Josh Stern wrote:

> Hi, I'm wondering if there is any built-in PHP primitives to perform the
> same task as this simple, almost trivial function:
> 
> function get(&$var) {
>      return $var;
> }
> 
> ?
> 
> 
> It is useful for accessing arrays where some fields may be unset.  For
> example:
> 
> ************************************************
> 
> <?php
> 
> 
> function get(&$var) {
>      return $var;
> }
> 
> $arr = array();
> $arr[5] = 'sam';
> $arr[2] = 'chris';
> $arr[3] = null;
> 
> $fromGet5 =  get($arr[5]);
> $fromGet1 = get($arr[1]);
> 
> echo "Value of fromGet5 is $fromGet5\n";
> echo "Value of fromGet1 is $fromGet1\n";
> 
> $fromGet5 = 'fred';
> 
> echo "Value of fromGet5 is now $fromGet5\n";
> 
> echo "Value of arr[5] is still $arr[5]\n";
> 
> **************************************************
> 
> 
> Assigning the value directly, without the function, as in <$fromGet1 =
> &$arr[1]> transfers the value & the reference, which is undesirable &
> likely to lead to hard to detect bugs.  Assignment without a reference
> generates errors for undefined array keys.
> 
> The inline code  (isset($arr[1]) ? $arr[1] : NULL) is cumbersome to keep
> typing over & over again & logically might be less efficient since it
> appears to fetch arr[1] twice, though there may be some hidden
> optimization.

As of PHP 7.0.0 there is the null coalescing opertor, so you can write:

  $arr[1] ?? NULL

> It seems like there should be a built in primitive called 'get' or
> 'ifset' that does this task.

See
<https://nikic.github.io/2014/01/10/The-case-against-the-ifsetor-function.html>.

> Wondering how others handle this issue & what I might be missing...

-- 
Christoph M. Becker

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php