在PHP中为数组添加值的最快方法是什么

问题描述:

I'm working on a project that has an Arr helper class and I am curious about something: Is there a benefit in doing this:

/**
 * Sets an array value
 *
 * @param array  $array
 * @param string $path
 * @param mixed  $value
 *
 * @return void
 */
public static function set(array &$array, $path, $value)
{
    $segments = explode('.', $path);
    while (count($segments) > 1) {
        $segment = array_shift($segments);
        if ( ! isset( $array[$segment] ) || ! is_array($array[$segment])) {
            $array[$segment] = [];
        }
        $array =& $array[$segment];
    }
    $array[array_shift($segments)] = $value;
}

Arr::set($data['stories'], 'fields.age', '3');

Over this:

$data['stories']['fields']['age'] = '3';

Or is there a better, faster way?

The function is just easier to type - you do not have to make so many brackets and quotation mark. It makes things easier.

For performance: If you set the array values with normal syntax, it is faster, because you do not have to explode the path or check for existence before. But this takes not so many time.