473,473 Members | 2,134 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Associative array within fuction

37 New Member
Hi
I could really do with some help here :)
I am tring to display all of the results from the array without having to write everything out by hand like this

Expand|Select|Wrap|Line Numbers
  1.     echo get_currency(1, GBP);
  2.     echo "<br>";
  3.     echo get_currency(1, USD);
  4.     echo "<br>";
  5.     echo get_currency(2, NZD);
  6.     echo "<br>";
  7.  
I have been trying to use a for each loop but the array name ($aExchangeRates) is returned as undefined.
Expand|Select|Wrap|Line Numbers
  1. foreach ($prices as $key => $value)
  2.  echo $key.'=>'.$value.'<br />';
  3.  
First goal is to display contents of array.

Second step...try to put those values into function to return $result :)

tyvm to anyone who takes pity on a noob

Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3.  
  4.  
  5.     define('NZD', 'english-nz');
  6.     define('GBP', 'english-uk');
  7.     define('USD', 'american-english');
  8.  
  9.     function get_currency($iPrice, $original_currency)
  10.     {
  11.  
  12.         //-------Associative Array--------------------------//
  13.         $aExchangeRates = array    (    
  14.  
  15.         //-------values in relation to the US dollar--------//
  16.  
  17.                                     'GBP' => '0.552272',
  18.                                     'USD' => '1',
  19.                                     'NZD' => '1.48695'
  20.  
  21.                                 );
  22.  
  23.         setlocale(LC_MONETARY, $original_currency);
  24.  
  25.         //-----localeconv()-----//
  26.         //-----Returns an associative array containing localized numeric and monetary formatting information-----//
  27.         $converting_currency = localeconv();
  28.  
  29.         $iExchangeRate = $aExchangeRates[trim($converting_currency['int_curr_symbol'])];
  30.         $iTotal = $iPrice * $iExchangeRate;
  31.  
  32.         $result = $converting_currency['currency_symbol'] . number_format($iTotal, 5);
  33.  
  34.         return $result;
  35.  
  36. }        
  37.  
  38.     echo get_currency(1, GBP);
  39.     echo "<br>";
  40.     echo get_currency(1, USD);
  41.     echo "<br>";
  42.     echo get_currency(2, NZD);
  43.     echo "<br>";
  44.  
  45.  
  46. ?>
  47.  
Sep 19 '08 #1
11 2045
Atli
5,058 Recognized Expert Expert
Hi.

Are you trying to replace the echo statements at the bottom?

Then the problem is most likely that you are defining your array inside a function, and then trying to use that array outside the function.

Anything created inside a function will only exists inside that function, unless it is somehow made to exist elsewhere. (via the return keyword or something like that).

Try creating your array outside the function, and import it into the function if you need it.
Sep 19 '08 #2
lozwaldo
37 New Member
Sorry I made a mistake with this reply and don't know how to delete it :)
Sep 20 '08 #3
lozwaldo
37 New Member
Hi.

Are you trying to replace the echo statements at the bottom?

Then the problem is most likely that you are defining your array inside a function, and then trying to use that array outside the function.

Anything created inside a function will only exists inside that function, unless it is somehow made to exist elsewhere. (via the return keyword or something like that).

Try creating your array outside the function, and import it into the function if you need it.
Tyvm :)

I decleared the array outside of the function and then decleared a global var inside the function. Not sure if this is the best wat to do it but it works.

I have the Foreach loop working well but am having trouble calling and executing the function in the Foreach loop.

Goal:
Loop through array and apply function to the values and then output the result.
Expand|Select|Wrap|Line Numbers
  1.     foreach($aExchangeRates as $key => $value)
  2. {
  3.     echo get_currency($money, "What goes here"). "<br>";
  4. }
  5.  
  6.  
Any help would be awesome

cheers

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3.         //-------Associative Array--------------------------//
  4.         $aExchangeRates = array    (            
  5.         //-------values in relation to the US dollar--------//                                    
  6.                                     'GBP' => '0.552272',
  7.                                     'USD' => '1',
  8.                                     'NZD' => '1.48695'
  9.                                 );
  10. $money = 10;
  11.  
  12.         //-------Constants--------------------------//
  13.     define('NZD', 'english-nz');
  14.     define('GBP', 'english-uk');
  15.     define('USD', 'american-english');    
  16.  
  17.     function get_currency($iPrice, $original_currency)
  18.     {                                    
  19.         setlocale(LC_MONETARY, $original_currency);
  20.  
  21.         //-----localeconv()-----//
  22.         $converting_currency = localeconv();
  23.         global    $aExchangeRates;
  24.  
  25.         $iExchangeRate = $aExchangeRates[trim($converting_currency['int_curr_symbol'])];
  26.         $iTotal = $iPrice * $iExchangeRate;
  27.  
  28.         $result = $converting_currency['currency_symbol'] . number_format($iTotal, 5);
  29.  
  30.         return $result;
  31.  
  32. }        
  33.     echo get_currency($money, GBP). "<br>";
  34.     echo "<br>";
  35.     echo get_currency($money, USD). "<br>";
  36.     echo "<br>";
  37.  
  38.     foreach($aExchangeRates as $key => $value)
  39. {
  40. echo $key . " - ". $value . "<br>";
  41. }
  42. ?>
  43.  
  44.  
Sep 20 '08 #4
Atli
5,058 Recognized Expert Expert
If I'm reading this correctly, you would pass the $value of the foreach loop into the second parameter of your function.
That would be the name of the locale you want to convert into.

The first parameter would be the dollar amount you want converted.
Sep 20 '08 #5
lozwaldo
37 New Member
If I'm reading this correctly, you would pass the $value of the foreach loop into the second parameter of your function.
That would be the name of the locale you want to convert into.

The first parameter would be the dollar amount you want converted.

Thats correct. Have tried
Expand|Select|Wrap|Line Numbers
  1.     foreach($aExchangeRates as $key => $value)
  2. {
  3.     echo get_currency($money, $iExchangeRate). "<br>";
  4. }
  5.  
but get this error message

Notice: Undefined variable: iExchangeRate in C:\Program Files\Apache\htdocs\currency2.php on line 37
$14.86950

Expand|Select|Wrap|Line Numbers
  1. Line 37 is
  2. echo get_currency($money, $iExchangeRate). "<br>";
  3.  
I have tried making $iExchangeRate global but no joy. If function logic is

Expand|Select|Wrap|Line Numbers
  1. $iTotal = $iPrice * $iExchangeRate;
Converted currency = $money * $iExchangeRate

any thoughts please :)
Sep 21 '08 #6
Atli
5,058 Recognized Expert Expert
You loop through the $aExchangeRates array so you can use each value from it.
So you should be passing the $value of the foreach loop into the function call:
Expand|Select|Wrap|Line Numbers
  1. foreach($aExchangeRates as $value)
  2. {
  3.     echo get_currency($money, $value). "<br>";
  4. }
  5.  
And there is no need for the $key part you added, so I removed that.

Check out foreach loops in the manual if this isn't making sense.
Sep 21 '08 #7
lozwaldo
37 New Member
You loop through the $aExchangeRates array so you can use each value from it.
So you should be passing the $value of the foreach loop into the function call:
Expand|Select|Wrap|Line Numbers
  1. foreach($aExchangeRates as $value)
  2. {
  3.     echo get_currency($money, $value). "<br>";
  4. }
  5.  
And there is no need for the $key part you added, so I removed that.

Check out foreach loops in the manual if this isn't making sense.
I have reread the manual.

Expand|Select|Wrap|Line Numbers
  1. /*example 1 - Basic loop thru assoc array*/
  2. foreach($aExchangeRates as $key => $value)
  3. {
  4.     echo $key . " - ". $value . "<br>";
  5.  
  6. }
  7.  
  8. /*example 2 - looping values and passing thru function*/
  9. foreach($aExchangeRates as $value)
  10. {
  11.     echo get_currency($money, $value). "<br>";
  12. }
  13.  
example 1 - works fine
example 2 - gives this error message

Notice: Undefined index: in C:\Program Files\Apache\htdocs\currency2.php on line 25
0.00000

my understanding of this error is : referring to an array element that does not exist.

Example 1 - works and uses $value so it exists???

I can see now that $value is the right value to pass thru the function. I just don't know how to reference it in example 2.

I'm such a moron :) I really appreciate your help and have tried everything I know. I just don't know where to go from here.

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3.         //-------Associative Array--------------------------//
  4.         $aExchangeRates = array    (            
  5.         //-------values in relation to the US dollar--------//                                    
  6.                                     'GBP' => '0.552272',
  7.                                     'USD' => '1',
  8.                                     'NZD' => '1.48695'
  9.                                 );
  10. $money = 10;
  11.  
  12.         //-------Constants--------------------------//
  13.     define('NZD', 'english-nz');
  14.     define('GBP', 'english-uk');
  15.     define('USD', 'american-english');    
  16.  
  17.     function get_currency($iPrice, $original_currency)
  18.     {                                    
  19.         setlocale(LC_MONETARY, $original_currency);
  20.  
  21.         //-----localeconv()-----//
  22.         $converting_currency = localeconv();
  23.         global    $aExchangeRates;
  24.  
  25.         $iExchangeRate = $aExchangeRates[trim($converting_currency['int_curr_symbol'])];
  26.         $iTotal = $iPrice * $iExchangeRate;
  27.  
  28.         $result = $converting_currency['currency_symbol'] . number_format($iTotal, 5);
  29.  
  30.         return $result;
  31.  
  32. }        
  33.  
  34.  
  35.  
  36. /*Basic loop thru assoc array*/
  37. foreach($aExchangeRates as $key => $value)
  38. {
  39.     echo $key . " - ". $value . "<br>";
  40.  
  41. }
  42.  
  43. /*looping values and passing thru function*/
  44. foreach($aExchangeRates as $value)
  45. {
  46.     echo get_currency($money, $value). "<br>";
  47. }
  48.  
  49. ?>
  50.  
Sep 21 '08 #8
Atli
5,058 Recognized Expert Expert
Ok. The undefined index problem isn't referring to the foreach loop now.

It's all that locale stuff in your function that isn't working. The locale isn't being set properly, so when you try to read the values based on the set locale, they don't exists and you get this warning.

Why do you have all this locale stuff there?
Is it just to get the correct currency symbol?

It would be much easier to just add that to your exchange rate array as well, to avoid these sort of problems.
Sep 21 '08 #9
lozwaldo
37 New Member
Ok. The undefined index problem isn't referring to the foreach loop now.

It's all that locale stuff in your function that isn't working. The locale isn't being set properly, so when you try to read the values based on the set locale, they don't exists and you get this warning.

Why do you have all this locale stuff there?
Is it just to get the correct currency symbol?

It would be much easier to just add that to your exchange rate array as well, to avoid these sort of problems.
I took your great advice and simplified the code :) Yay it works........

one small question. This is returned:

Exchange Rates USD
GBP - 0.552272
USD - 1
NZD - 1.48695

10 US Dollars buys you:
NZD - 5.52272
NZD - 10.00000
NZD - 14.86950

I have tried putting in $key to show currency type but it is taking last value and applying it to all.

any ideas - then i'll go away

ty so much for your help and advice. I've learnt a LOT

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.         //-------Associative Array--------------------------//
  3.         $aExchangeRates = array    (            
  4.         //-------values in relation to the US dollar--------//                                    
  5.                                     'GBP' => '0.552272',
  6.                                     'USD' => '1',
  7.                                     'NZD' => '1.48695'
  8.                                 );
  9. $money = 10;
  10.  
  11.     function get_currency($iPrice, $original_currency)
  12.     {                                            
  13.         $iTotal = $iPrice * $original_currency;        
  14.         $result = number_format($iTotal, 5);        
  15.         return $result;    
  16. }        
  17.  
  18.     echo "Exchange Rates USD"."<br>";    
  19.     /*Basic loop thru assoc array*/
  20.     foreach($aExchangeRates as $key => $value)
  21. {
  22.     echo $key . " - ". $value . "<br>";    
  23. }
  24.  
  25.     echo "<br>";
  26.     echo $money." US Dollars buys you:"."<br>";    
  27.  
  28.     /*looping values and passing thru function*/
  29.     foreach($aExchangeRates as $value)
  30. {
  31.     echo $key." - ". get_currency($money, $value)."<br>";
  32. }
  33.  
  34. ?>
  35.  
Sep 21 '08 #10
Atli
5,058 Recognized Expert Expert
Glad you got it to work :)

As for the problem. Your second loop doesn't set a $key value, so the last $key from your first loop is being used throughout the entire second loop.

You need to have your second loop set the $key value, like your fist loop does.
Sep 21 '08 #11
lozwaldo
37 New Member
Glad you got it to work :)

As for the problem. Your second loop doesn't set a $key value, so the last $key from your first loop is being used throughout the entire second loop.

You need to have your second loop set the $key value, like your fist loop does.

Cheers

Everything is working as it should :)

ty so much. I really appreciate your patience and help.

Loz
Sep 21 '08 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

27
by: Abdullah Kauchali | last post by:
Hi folks, Can one rely on the order of keys inserted into an associative Javascript array? For example: var o = new Object(); o = "Adam"; o = "Eve";
6
by: mark4asp | last post by:
Suppose I have the following code. It functions to randomly select a city based upon the probabilities given by the key differences in the associative array. . Eg. because the key difference...
26
by: JGH | last post by:
How can I check if a key is defined in an associative array? var users = new array(); users = "Joe Blow"; users = "John Doe"; users = "Jane Doe"; function isUser (userID) { if (?????)
4
by: Robert | last post by:
I am curious why some people feel that Javascript doesn't have associative arrays. I got these definitions of associative arrays via goggle: Arrays in which the indices may be numbers or...
8
by: Derek Basch | last post by:
Is there any way to associate name/value pairs during an array initialization? Like so: sType = "funFilter" filterTypeInfo = ; filterTypeInfo = new Array("type" : sType); I can do it using...
47
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they...
35
by: VK | last post by:
Whatever you wanted to know about it but always were affraid to ask. <http://www.geocities.com/schools_ring/ArrayAndHash.html>
7
by: Robert Mark Bram | last post by:
Hi All! How do you get the length of an associative array? var my_cars= new Array() my_cars="Mustang"; my_cars="Station Wagon"; my_cars="SUV"; alert(my_cars.length);
41
by: Rene Nyffenegger | last post by:
Hello everyone. I am not fluent in JavaScript, so I might overlook the obvious. But in all other programming languages that I know and that have associative arrays, or hashes, the elements in...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.