Associative array within fuction

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lozwaldo
    New Member
    • Feb 2008
    • 37

    Associative array within fuction

    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

    Code:
    	echo get_currency(1, GBP);
    	echo "<br>";
    	echo get_currency(1, USD);
    	echo "<br>";
    	echo get_currency(2, NZD);
    	echo "<br>";
    I have been trying to use a for each loop but the array name ($aExchangeRate s) is returned as undefined.
    Code:
    foreach ($prices as $key => $value)
     echo $key.'=>'.$value.'<br />';
    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

    Code:
    <?php
    
    
    	define('NZD', 'english-nz');
    	define('GBP', 'english-uk');
    	define('USD', 'american-english');
    	
    	function get_currency($iPrice, $original_currency)
    	{
    		
    		//-------Associative Array--------------------------//
    		$aExchangeRates = array	(	
    		
    		//-------values in relation to the US dollar--------//
    									
    									'GBP' => '0.552272',
    									'USD' => '1',
    									'NZD' => '1.48695'
    	
    								);
    							
    		setlocale(LC_MONETARY, $original_currency);
    		
    		//-----localeconv()-----//
    		//-----Returns an associative array containing localized numeric and monetary formatting information-----//
    		$converting_currency = localeconv();
    	    
    	    $iExchangeRate = $aExchangeRates[trim($converting_currency['int_curr_symbol'])];
    	    $iTotal = $iPrice * $iExchangeRate;
    		
    		$result = $converting_currency['currency_symbol'] . number_format($iTotal, 5);
    		
    		return $result;
    	
    }		
    
    	echo get_currency(1, GBP);
    	echo "<br>";
    	echo get_currency(1, USD);
    	echo "<br>";
    	echo get_currency(2, NZD);
    	echo "<br>";
    	
    
    ?>
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    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.

    Comment

    • lozwaldo
      New Member
      • Feb 2008
      • 37

      #3
      Sorry I made a mistake with this reply and don't know how to delete it :)
      Last edited by lozwaldo; Sep 20 '08, 11:09 AM. Reason: Mistake in replying

      Comment

      • lozwaldo
        New Member
        • Feb 2008
        • 37

        #4
        Originally posted by Atli
        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.
        Code:
        	foreach($aExchangeRates as $key => $value)
        {
        	echo get_currency($money, "What goes here"). "<br>";
        }
        Any help would be awesome

        cheers

        Code:
        <?php
        
        		//-------Associative Array--------------------------//
        		$aExchangeRates = array	(			
        		//-------values in relation to the US dollar--------//									
        									'GBP' => '0.552272',
        									'USD' => '1',
        									'NZD' => '1.48695'
        								);
        $money = 10;
        
        		//-------Constants--------------------------//
        	define('NZD', 'english-nz');
        	define('GBP', 'english-uk');
        	define('USD', 'american-english');	
        	
        	function get_currency($iPrice, $original_currency)
        	{									
        		setlocale(LC_MONETARY, $original_currency);
        		
        		//-----localeconv()-----//
        		$converting_currency = localeconv();
        	    global	$aExchangeRates;
        
        	    $iExchangeRate = $aExchangeRates[trim($converting_currency['int_curr_symbol'])];
        	    $iTotal = $iPrice * $iExchangeRate;
        		
        		$result = $converting_currency['currency_symbol'] . number_format($iTotal, 5);
        		
        		return $result;
        	
        }		
        	echo get_currency($money, GBP). "<br>";
        	echo "<br>";
        	echo get_currency($money, USD). "<br>";
        	echo "<br>";
        	
        	foreach($aExchangeRates as $key => $value)
        {
        echo $key . " - ". $value . "<br>";
        }
        ?>

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          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.

          Comment

          • lozwaldo
            New Member
            • Feb 2008
            • 37

            #6
            Originally posted by Atli
            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
            Code:
            	foreach($aExchangeRates as $key => $value)
            {
            	echo get_currency($money, $iExchangeRate). "<br>";
            }
            but get this error message

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

            Code:
            Line 37 is
            echo get_currency($money, $iExchangeRate). "<br>";
            I have tried making $iExchangeRate global but no joy. If function logic is

            Code:
            $iTotal = $iPrice * $iExchangeRate;
            Converted currency = $money * $iExchangeRate

            any thoughts please :)

            Comment

            • Atli
              Recognized Expert Expert
              • Nov 2006
              • 5062

              #7
              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:
              Code:
              foreach($aExchangeRates as $value)
              {
              	echo get_currency($money, $value). "<br>";
              }
              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.

              Comment

              • lozwaldo
                New Member
                • Feb 2008
                • 37

                #8
                Originally posted by Atli
                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:
                Code:
                foreach($aExchangeRates as $value)
                {
                	echo get_currency($money, $value). "<br>";
                }
                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.

                Code:
                /*example 1 - Basic loop thru assoc array*/
                foreach($aExchangeRates as $key => $value)
                {
                	echo $key . " - ". $value . "<br>";
                	
                }
                
                /*example 2 - looping values and passing thru function*/
                foreach($aExchangeRates as $value)
                {
                	echo get_currency($money, $value). "<br>";
                }
                example 1 - works fine
                example 2 - gives this error message

                Notice: Undefined index: in C:\Program Files\Apache\ht docs\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.

                Code:
                <?php
                
                		//-------Associative Array--------------------------//
                		$aExchangeRates = array	(			
                		//-------values in relation to the US dollar--------//									
                									'GBP' => '0.552272',
                									'USD' => '1',
                									'NZD' => '1.48695'
                								);
                $money = 10;
                
                		//-------Constants--------------------------//
                	define('NZD', 'english-nz');
                	define('GBP', 'english-uk');
                	define('USD', 'american-english');	
                	
                	function get_currency($iPrice, $original_currency)
                	{									
                		setlocale(LC_MONETARY, $original_currency);
                		
                		//-----localeconv()-----//
                		$converting_currency = localeconv();
                	    global	$aExchangeRates;
                		
                	    $iExchangeRate = $aExchangeRates[trim($converting_currency['int_curr_symbol'])];
                	    $iTotal = $iPrice * $iExchangeRate;
                		
                		$result = $converting_currency['currency_symbol'] . number_format($iTotal, 5);
                		
                		return $result;
                	
                }		
                
                
                	
                /*Basic loop thru assoc array*/
                foreach($aExchangeRates as $key => $value)
                {
                	echo $key . " - ". $value . "<br>";
                	
                }
                
                /*looping values and passing thru function*/
                foreach($aExchangeRates as $value)
                {
                	echo get_currency($money, $value). "<br>";
                }
                
                ?>

                Comment

                • Atli
                  Recognized Expert Expert
                  • Nov 2006
                  • 5062

                  #9
                  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.

                  Comment

                  • lozwaldo
                    New Member
                    • Feb 2008
                    • 37

                    #10
                    Originally posted by Atli
                    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

                    Code:
                    <?php
                    		//-------Associative Array--------------------------//
                    		$aExchangeRates = array	(			
                    		//-------values in relation to the US dollar--------//									
                    									'GBP' => '0.552272',
                    									'USD' => '1',
                    									'NZD' => '1.48695'
                    								);
                    $money = 10;
                    	
                    	function get_currency($iPrice, $original_currency)
                    	{											
                    	    $iTotal = $iPrice * $original_currency;		
                    		$result = number_format($iTotal, 5);		
                    		return $result;	
                    }		
                    
                    	echo "Exchange Rates USD"."<br>";	
                    	/*Basic loop thru assoc array*/
                    	foreach($aExchangeRates as $key => $value)
                    {
                    	echo $key . " - ". $value . "<br>";	
                    }
                    
                    	echo "<br>";
                    	echo $money." US Dollars buys you:"."<br>";	
                    	
                    	/*looping values and passing thru function*/
                    	foreach($aExchangeRates as $value)
                    {
                    	echo $key." - ". get_currency($money, $value)."<br>";
                    }
                    
                    ?>

                    Comment

                    • Atli
                      Recognized Expert Expert
                      • Nov 2006
                      • 5062

                      #11
                      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.

                      Comment

                      • lozwaldo
                        New Member
                        • Feb 2008
                        • 37

                        #12
                        Originally posted by Atli
                        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

                        Comment

                        Working...