note 60866 added to language.operators.comparison

From: Date: Wed, 18 Jan 2006 19:36:34 +0000
Subject: note 60866 added to language.operators.comparison
Groups: php.notes 
Request: Send a blank email to php-notes+get-102053@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. /** * 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 } ---- Server IP: 12.160.245.96Probable Submitter: 67.10.16.29 ---- Manual Page -- http://www.php.net/manual/en/language.operators.comparison.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+60866 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60866&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60866&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60866&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60866&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60866&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60866&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60866&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+60866&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#102053) next »