Jump to content


This topic is now archived and is closed to further replies.


adding elements to arrays using variables as keys

Recommended Posts

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";

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

    default :
        $wordsize[]= "0";

        } //end switch

$totalofword = array_sum($wordsize);

                            } //end foreach letter

return $totalofword;

//$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>");

//end test section with functions


Share this post

Link to post
Share on other sites
[b]$array[$key] = $value[/b] should work. This code:

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

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

echo '<pre>';
echo '</pre>';

Would print:
    [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).

Share this post

Link to post
Share on other sites


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.