Help us understand the problem. What is going on with this article?

ドットチェイン表現で配列要素をget/set/unset

More than 3 years have passed since last update.

目的とする関数

パフォーマンス面はおいといて,利便性の面からこんな関数が欲しい.できればevalは使いたくない.

<?php

$array = [
    'a' => [
        'b' => [
            'c' => 1,
        ],
    ],
];

var_dump(array_get($array, 'a.b')); // ['c' => 1]
var_dump(array_get($array, 'a.b.c')); // int(1)
var_dump(array_get($array, 'a.b.x')); // NULL

array_set($array, 'a.b.d', 2);
var_dump(array_get($array, 'a.b')); // ['c' => 1, 'd' => 2]

array_unset($array, 'a.b.c');
var_dump(array_get($array, 'a.b')); // ['d' => 2]

array_unset($array, 'a.x');
var_dump(array_get($array, 'a')); // ['b' => ['d' => 2]]

array_unset($array, 'a');
var_dump($array); // []

実装

array_unsetだけちょっと複雑になってます.

  • 要素を削除するためには必ずが必要なので$currentを辿りつつ$parentも同時にずらしていく
  • 存在しない要素を参照代入で作ってしまわないようにarray_key_existsでのチェックが必要
<?php

function array_get(array $array, $path, $separator = '.') {
    $keys = explode($separator, $path);
    $current = $array;
    foreach ($keys as $key) {
        if (!isset($current[$key])) return;
        $current = $current[$key];
    }
    return $current;
}

function array_set(array &$array, $path, $value, $separator = '.') {
    $keys = explode($separator, $path);
    $current = &$array;
    foreach ($keys as $key) {
        $current = &$current[$key];
    }
    $current = $value;
}

function array_unset(array &$array, $path, $separator = '.') {
    $keys = explode($separator, $path);
    $current = &$array;
    $parent = &$array;
    foreach ($keys as $i => $key) {
        if (!array_key_exists($key, $current)) return;
        if ($i) $parent = &$current;
        $current = &$current[$key];
    }
    unset($parent[$key]);
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away