Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: array question

  1. #1
    New Coder
    Join Date
    May 2012
    Posts
    89
    Thanks
    51
    Thanked 0 Times in 0 Posts

    array question

    Hi

    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:

    PHP Code:
    $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 ();                
          die();        
       }            

    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.
    Last edited by shaunthomson; 10-07-2012 at 03:17 PM.

  • #2
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,395
    Thanks
    13
    Thanked 353 Times in 349 Posts
    there are some neat little array functions like array_diff() or array_intersect() to compare arrays.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • Users who have thanked Dormilich for this post:

    shaunthomson (10-17-2012)

  • #3
    New Coder
    Join Date
    May 2012
    Posts
    89
    Thanks
    51
    Thanked 0 Times in 0 Posts
    Thanks Dormilich - I'll check them out.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •