7
8

More than 5 years have passed since last update.

連想配列にデフォルト値を適用しつつ既知のキーだけ抽出

Last updated at Posted at 2013-08-06

Before

<?php
$params = array('a' => 9, 'c' => 3);

$default = array('a' => 1, 'b' => 2);
$ret = array();
foreach ($default as $k => $v)
{
    if (array_key_exists($k, $params))
    {
        $v = $params[$k];
    }
    $ret[$k] = $v;
}
$params = $ret;

After

foreach しなくてももっと簡単に書けます。

<?php
$params = array('a' => 9, 'c' => 3);

$default = array('a' => 1, 'b' => 2);
$params = array_intersect_key($params, $default) + $default;

コンストラクタで連想配列でコンフィグを受け取る系のライブラリなどで使えます。

<?php
class HogeClass
{
    protected $config = array(
        'attr1' => null,
        'attr2' => 123,
        'attr3' => "abc",
    );

    public function __construct(array $config)
    {
        $this->config = array_intersect_key($config, $this->config) + $this->config;
    }
}
7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8