11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2つの配列が同じものかどうかチェックするPHP関数

Posted at

PHPで、配列の内容が同じかどうかチェックしたい時に使う関数。
連想配列の階層が深くても可。

<?php

function is_same_array($array1 = null, $array2 = null)
{
    if (empty($array1) && empty($array2)) {
        return true;
    } elseif(
        (empty($array1) && !empty($array2))
        || (!empty($array1) && empty($array2))
    ) {
        return false;
    } elseif(
        (is_array($array1) && !is_array($array2))
        || (!is_array($array1) && is_array($array2))
    ) {
        return false;
    }

    foreach($array1 as $key => $value) {
        if (is_array($value)) {
            if (!isset($array2[$key])) {
                return false;
            } elseif(!is_array($array2[$key])) {
                return false;
            } elseif (!is_same_array($value, $array2[$key])) {
                return false;
            }
        } elseif(!array_key_exists($key, $array2) || $array2[$key] !== $value) {
            return false;
        }
    }

    return true;
}

機能としては「ただ同じかどうか判断するだけ」(返り値は truefalse のみ)なので、差分を返したりとかはナシ。
参考にしたのがこちらの関数で、こちらは差分を返してくれる模様。

パフォーマンスは悪そうだけど、配列の順番が違ってもチェックできるのがメリットかな・・・

11
10
3

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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?