note 60866 modified in language.operators.comparison by danbrown

From: Date: Thu, 18 Jun 2009 14:08:56 +0000
Subject: note 60866 modified in language.operators.comparison by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-157075@lists.php.net to get a copy of this message
You can't just compare two arrays with the === operator like you would think to find out if they are equal or not. This is more complicated when you have multi-dimensional arrays. Here is a recursive comparison function. <?php /** * Compares two arrays to see if they contain the same values. Returns TRUE or FALSE. * usefull for determining if a record or block of data was modified (perhaps by user input) * prior to setting a "date_last_updated" or skipping updating the db in the case of no change. * * @param array $a1 * @param array $a2 * @return boolean */ function array_compare_recursive($a1, $a2) { if (!(is_array($a1) and (is_array($a2)))) { return FALSE;} if (!count($a1) == count($a2)) { return FALSE; // arrays don't have same number of entries } foreach ($a1 as $key => $val) { if (!array_key_exists($key, $a2)) {return FALSE; // uncomparable array keys don't match } elseif (is_array($val) and is_array($a2[$key])) // if both entries are arrays then compare recursive {if (!array_compare_recursive($val,$a2[$key])) return FALSE; } elseif (!($val === $a2[$key])) // compare entries must be of same type. {return FALSE; } } return TRUE; // $a1 === $a2 } ?> --was-- You can't just compare two arrays with the === operator like you would think to find out if they are equal or not. This is more complicated when you have multi-dimensional arrays. Here is a recursive comparison function. /** * Compares two arrays to see if they contain the same values. Returns TRUE or FALSE. * usefull for determining if a record or block of data was modified (perhaps by user input) * prior to setting a "date_last_updated" or skipping updating the db in the case of no change. * * @param array $a1 * @param array $a2 * @return boolean */ function array_compare_recursive($a1, $a2) { if (!(is_array($a1) and (is_array($a2)))) { return FALSE;} if (!count($a1) == count($a2)) { return FALSE; // arrays don't have same number of entries } foreach ($a1 as $key => $val) { if (!array_key_exists($key, $a2)) {return FALSE; // uncomparable array keys don't match } elseif (is_array($val) and is_array($a2[$key])) // if both entries are arrays then compare recursive {if (!array_compare_recursive($val,$a2[$key])) return FALSE; } elseif (!($val === $a2[$key])) // compare entries must be of same type. {return FALSE; } } return TRUE; // $a1 === $a2 } http://php.net/manual/en/language.operators.comparison.php

« previous php.notes (#157075) next »