david_55 david_55 - 3 years ago 101
PHP Question

concatenate text values to access array item in php

I'm trying to create a function in php that will read from an array. I am trying to concatenate text and the array id number, to read the value in the array, however it is the concatenated text that is being returned, not the value of the array.

Here is my code:

//arrays with words in dictionary

$dictionary_word1 = array("test1","test2","test3");

$dictionary_word2 = array("test4","test5","test6");

$dictionary_word3 = array("test7","test8","test9");

$word_to_lookup = "dictionary_word_1";
//value to send to function

$returned_word = convert_word($word_to_lookup);
//value returned from function

echo "<br>the returned word from the function is " . $returned_word;
//the text "$dictionary_word_1[2]" is displayed instead of array value

echo "<br>the value in the array is " . $dictionary_word1[2];
//this displays correcty as "test3"

function convert_word($word_to_convert)
global $dictionary_word1;
$converted_word = '$'.$word_to_convert .'[2]';
return $converted_word;

Could anyone give me any tips on where I am going wrong?

Answer Source

You need to reference the variable this way to do what you are trying (see PHP: Variable Variables and PHP: Variable Parsing):

$converted_word = ${$word_to_convert}[2];

However, notice the difference between dictionary_word_1 and $dictionary_word1? Won't work.

Regardless, anytime you're doing this you would be better with an array. In this case a multidimensional array. Consider:

$words[1] = array("test1","test2","test3");
$words[2] = array("test4","test5","test6");
$words[3] = array("test7","test8","test9");

Then you're always using $words just changing the index and then using a word from that array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download