Jump to content


Photo

adding elements to arrays using variables as keys


  • Please log in to reply
1 reply to this topic

#1 madshadow

madshadow
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 27 May 2006 - 10:40 PM

hey everyone. I've come up with a bit of code below but i'm having problems with the end result. Specifically, the line

$masterarray[$key] = $finalsum;

I can't figure out how to add elements to an array using a key that comes from a variable. i would really appreciate any help on this..

//test section with functions

//going to be passed each element of the secondarray
function wordsum ($variable) {


$letterarray = str_split($variable);


foreach($letterarray as $letter) {


switch ($letter) {
    case "a":
        $wordsize[]= "1";
        break;

    case "b":
        $wordsize[]= "2";
        break;

    default :
        $wordsize[]= "0";


        } //end switch

$totalofword = array_sum($wordsize);



                            } //end foreach letter

return $totalofword;

//print_r($wordsize);
//$masterarray[$counter] = $totalofword;


} //end function wordsum


foreach($secondarray as $word) {//for each word

$finalsum = wordsum($word);

print(wordsum($word) . "<bR>");

$key = array_search($word, $secondarray);
print("<b>" . "$key" . "</b>");

$masterarray[$key] = $finalsum;





}//end foreach word


print("<br>" . "this is the final output" . "<br>");
print_r(array_values($masterarray));

// 
//end test section with functions



#2 poirot

poirot
  • Members
  • PipPipPip
  • Advanced Member
  • 646 posts
  • LocationAustin, TX

Posted 28 May 2006 - 12:07 AM

$array[$key] = $value should work. This code:
<?php

$key = 'red';
$value = 'apple';
$key2 = 'purple';
$value2 = 'grape';

$array[$key] = $value;
$array[$key2] = $value2;

echo '<pre>';
print_r($array);
echo '</pre>';

?>
Would print:
Array
(
    [red] => apple
    [purple] => grape
)
Maybe you can tell us what you are trying to do with it?
And also $totalofword = array_sum($wordsize) shouldn't be in the foreach loop (if you are trying to do what I think).
~ D Kuang




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users