madshadow Posted May 27, 2006 Share Posted May 27, 2006 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..[code]//test section with functions//going to be passed each element of the secondarrayfunction 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 letterreturn $totalofword;//print_r($wordsize);//$masterarray[$counter] = $totalofword;} //end function wordsumforeach($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 wordprint("<br>" . "this is the final output" . "<br>");print_r(array_values($masterarray));// //end test section with functions[/code] Quote Link to comment https://forums.phpfreaks.com/topic/10605-adding-elements-to-arrays-using-variables-as-keys/ Share on other sites More sharing options...
poirot Posted May 28, 2006 Share Posted May 28, 2006 [b]$array[$key] = $value[/b] should work. This code:[code]<?php$key = 'red';$value = 'apple';$key2 = 'purple';$value2 = 'grape';$array[$key] = $value;$array[$key2] = $value2;echo '<pre>';print_r($array);echo '</pre>';?>[/code]Would print:[code]Array( [red] => apple [purple] => grape)[/code]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). Quote Link to comment https://forums.phpfreaks.com/topic/10605-adding-elements-to-arrays-using-variables-as-keys/#findComment-39571 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.