View Full Version : array question

10-07-2012, 04:12 PM

I've almost solved my array problem, but am just wondering if there is a better way to do this?

I have an array of ids stored in a $_SESSION var (from a previous page load), and when the page loads again, it gets a new array of ids from mysql. I want to compare the arrays (in the fastest way possible) to see if they are different, and if so, go do myfunc(). I'm not worried if the order has changed, just if there is a new id or one missing.

My code first does a simple sizeof comparison, and if there is a difference, no need to do any more testing, go straight to myfunc().

Bu if the sizes are the same, the id might still have changed, so my code then checks them like this:

$new_array_size = sizeof($new_array);

for($i = 0, $size = $new_array_size; $i < $size; ++$i) {

if ($new_array[$i] != $_SESSION['last_array'][$i])
myfunc ();

This works, except if the order of $_SESSION['last_array'] happens to get changed in another page.

I'm guessing the fix is to do a sort() of each array before the loop, but I'm wondering if there is a faster way overall to do it?

I tried figuring a way with isset after doing an array_flip, but array_flip didn't seem to swap keys and values in my arrays.

I would have used in_array, but I've read so many times that it's slow.

Thanks for your help.

10-08-2012, 11:16 AM
there are some neat little array functions like array_diff() (http://php.net/array-diff) or array_intersect() (http://php.net/array-intersect) to compare arrays.

10-17-2012, 04:25 AM
Thanks Dormilich - I'll check them out.