Hi, hopefully this is an easy one for somone.. i've been pulling my hair out though..

I am creating an array of values which needs to be then passed to a function.

Everything works when I create it like this:

$myarray = array('value1'=>2,'value1'=>1,'value1'=>2,'value1'=>1);

However as i don't know how many elements there will be I, I am building a text string comtaining the values first inside a loop. so for each iteration of the loop I do this:

$arraystring = $arraystring."'".$field1name."'".'=>'.$field2name.',';

Then I remove the last comma and add a prefix:

$finalarraystring = 'array('.substr($arraystringstring,'',-1).')';

So effectivly I end up with a string called $finalarraystring which equals something like:


So what I am trying to do is to then create my array using this text string, but of course it is not working as it thinks I am trying to assign a string to my array.

I am trying

$array  = $finalarraystring;
$array  = '$finalarraystring';
$array  = "$finalarraystring";

but nothings works. help!

9 Years
Discussion Span
Last Post by oconndav

Something like this might be simpler if it is possible for your code:

// $elements is your list of elements that you are adding to your string array
$arrayString = array();
foreach($elements as $element)
  $arrayString[] = $element;

Now, in your $arrayString you will need to access each element as $arrayString[0], $arrayString[1] etc instead of $arrayString and so on.


thanks darkagn,

although i'm not sure if I can do that.. becuase I need to reference the keys in the function (as well as the values).

Sorry I should have been clearer. I am passing the array into a function which will create a tag cloud. So the array contains each of the tags names and associated count.

So the array i pass needs to look like this:

$array = array('tag1'=>5,'tag3'=>10,'tag2'=>2,'tag26'=>3);

I am pulling the tag names and count values in from a MySQL query. It works fine when I hardcode type the array so my function works and I know that the array design is fine.

And as I said I have figured out how to dynamically build a string which looks exactly like the array (to the right of the equals above).

I was hoping that I can somehow force PHP to resolve the string as part of the array creation line.

So when I type:

$array = $stringibuilt

I want PHP to interperate it as:

$tags = array('tag1'=>5,'tag3'=>10,'tag2'=>2,'tag26'=>3);

..becuase that's what the string $stringibuilt contains.

OK the very fact that i'm struggling to explain this probably means i'm going about it the wrong way right?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.