Jump to content

Combination pairs of currencies


silkfire

Recommended Posts

Hey all I've found some combination functions out there but they're not working really like I want.

 

I have an array with some currencies:

 

array('SEK', 'EUR', 'USD', 'GBP', 'DKK', 'NOK', 'ISK');

 

Now I want the function to generate an array with all possible pairs:

 

array(array('SEK', 'EUR'), array('SEK', 'USD') ...)

 

It must allow for the inverse form: EUR, SEK is different from SEK, EUR.

 

But trash all pairs that are equal: SEK, SEK or EUR, EUR.

 

Help me out?

Link to comment
Share on other sites

It's a little loopy, but this appears to work:

 

// Loop through each currency
foreach ($currencies as $currency)
{
    // Loop through the currencies again to access the others
    foreach ($currencies as $other_currency)
    {
        // Check it's not the same
        if ($currency == $other_currency)
        {
            continue;
        }

        // Check this pair doesn't already exist
        foreach ($currency_pairs as $currency_pair)
        {
            if (($currency_pair[0] == $currency && $currency_pair[1] == $other_currency)
             || ($currency_pair[1] == $currency && $currency_pair[0] == $other_currency))
            {
                continue 2;
            }
        }

        // Add to pairs array
        $currency_pairs[] = array($currency, $other_currency);
    }
}

print_r($currency_pairs);

 

Edit.. again

 

I've actually written that so EUR - SEK, and SEK - EUR are classed as the same. To treat them differently, change the IF to this:

 

            if ($currency_pair[0] == $currency && $currency_pair[1] == $other_currency)
            {
                continue 2;
            }

 

Edit.. again.. again

 

Ha.. actually you can just remove the entire foreach loop there if that's the case.. the same order will never come up twice.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.