Tuesday, November 1, 2011

[php] Standard get() and getr()

Would you prefer $myarray['apple'] to return null when that index doesn't exist, rather than Notice: Undefined index: apple? How about $myobj->banana to return null rather than Notice: Undefined property: stdClass::$banana? Here's a simple getter to accommodate these fervent desires.

function get($e, $id, $default = null) {
  if (is_array($e))
    return isset($e[$id]) ? $e[$id] : $default;
  else if (is_object($e))
    return isset($e->$id) ? $e->$id : $default;
  else 
    return $default;
}
$result = get($myarray, 'apple');  // instead of $myarray['apple']
$result = get($myobj, 'banana');   // instead of $myobj->banana

Another useful getter is getr, which can navigate recursively through nested object/array hierarchies (and bail out gracefully at any point it runs into an undefined.)

function getr($e, $prop, $default = null) {
  if (strpos($prop, '.') !== false) {
    $props = explode('.', $prop, 2);
    $e0 = get($e, $props[0]);
    if ($e0 === null)
      return $default;
    else 
      return getr($e0, $props[1], $default);
  } else {
    return get($e, $prop, $default);
  }
}
$myrec1->name = array('first'=>'Joe','last'=>'Blow');
$myrec2->name = null;
echo getr($myrec1, 'name.last');  // returns 'Blow'
echo getr($myrec2, 'name.last');  // returns null

No comments: