Files
spa-api/system/arr.php

42 lines
948 B
PHP
Raw Normal View History

<?php namespace System;
class Arr {
/**
* Get an item from an array.
*
* If the specified key is null, the entire array will be returned. The array may
2011-08-09 14:31:57 -05:00
* also be accessed using JavaScript "dot" style notation. Retrieving items nested
* in multiple arrays is also supported.
*
* <code>
* // Returns "taylor"
* $item = Arr::get(array('name' => 'taylor'), 'name', $default);
*
* // Returns "taylor"
* $item = Arr::get(array('name' => array('is' => 'taylor')), 'name.is');
* </code>
2011-07-07 23:00:40 -05:00
*
* @param array $array
2011-06-16 22:27:57 -05:00
* @param string $key
* @param mixed $default
* @return mixed
*/
2011-06-16 22:27:57 -05:00
public static function get($array, $key, $default = null)
{
2011-08-08 08:27:12 -05:00
if (is_null($key)) return $array;
2011-08-02 13:38:50 -05:00
foreach (explode('.', $key) as $segment)
{
if ( ! array_key_exists($segment, $array))
2011-08-02 13:38:50 -05:00
{
return is_callable($default) ? call_user_func($default) : $default;
}
$array = $array[$segment];
}
return $array;
}
}