arr.php 1.34 KB
Newer Older
1 2 3 4 5 6 7
<?php namespace System;

class Arr {

	/**
	 * Get an item from an array.
	 *
8
	 * If the specified key is null, the entire array will be returned. The array may
9 10 11
	 * also be accessed using JavaScript "dot" style notation. Retrieving items nested
	 * in multiple arrays is also supported.
	 *
12
	 * @param  array   $array
13
	 * @param  string  $key
14
	 * @param  mixed   $default
15 16
	 * @return mixed
	 */
17
	public static function get($array, $key, $default = null)
18
	{
Taylor Otwell committed
19
		if (is_null($key)) return $array;
20

Taylor Otwell committed
21 22
		foreach (explode('.', $key) as $segment)
		{
23
			if ( ! array_key_exists($segment, $array))
Taylor Otwell committed
24 25 26 27 28 29 30 31 32 33
			{
				return is_callable($default) ? call_user_func($default) : $default;
			}

			$array = $array[$segment];
		}

		return $array;
	}

Taylor Otwell committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	/**
	 * Set an item in an array.
	 *
	 * This method is primarly helpful for setting the value in an array with
	 * a variable depth, such as configuration files.
	 *
	 * Like the Arr::get method, JavaScript "dot" syntax is supported.
	 *
	 * @param  array   $array
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return void
	 */
	public static function set(&$array, $key, $value)
	{
		$reference =& $array;

		foreach (explode('.', $key) as $segment)
		{
			if ( ! isset($reference[$segment]))
			{
				$reference[$segment] = $value;
				
				return;		
			}

			$reference =& $reference[$segment];
		}

		$reference = $value;
	}

66
}