can i create dynamic array variable names in php?
my requirement is...

i want a no: of 1-d arrays like $c1[],$c2[],$c3[].

and i need to dynamically create the arrays like this..

for($i=1;$i<$var;$i++)
$c.$i[]=$r;

is there any way to do this?

Recommended Answers

All 2 Replies

can i create dynamic array variable names in php?
my requirement is...

i want a no: of 1-d arrays like $c1[],$c2[],$c3[].

and i need to dynamically create the arrays like this..

for($i=1;$i<$var;$i++)
$c.$i[]=$r;

is there any way to do this?

Use $$. This evaluates the string value of the inner $ as the variable name.

eg:

$name = 'joe';

$$name = 'hello I am joe';

echo $joe; // hello I am joe

Use {} for disambiguation and precedence.

Eg:

for($i=1;$i<$var;$i++)
${$c.$i}[]=$r;

Why do you need to create the variable names dynamically?

I am trying to retrieve numbers from a mysql column, not all of the numbers just certain ones based on company name and test_taken_id. I can do this no problem if I want to hardscript it, but I don't want that. I want the user to enter the company name and the php to figure the rest out and I can't figure out how to do it dynamically. Let me give you an example. I have many users that have taken 3 tests, test #1, #2 and #3. I want to find out how many problems correct user #4 got on test #2, how can I get that? I can add up totals for all three tests for user #4 but I can't distinguish which is for what. This is the code I use that filters the "Test_taken_ID"s, so that I know which tests have been taken by a specific company. (I use my own functions to get the answers).

$company_test_numbers2 = mysql_query($result, $connection);
$new_uniques = filtering_array_columns($company_test_numbers2, 'test_taken_id');
echo "Test taken IDs: ";
echo "<pre>".print_r($new_uniques)."</pre>";

With another query I can get the names of the users who took those particular tests for that company:

$company_correct = mysql_query($result, $connection);
$name_uniques = filtering_array_columns($company_correct, 'username_id');
echo "Names of test takers: ";
echo "<pre>".print_r($name_uniques)."</pre>";

But I need to separate the different tests and add up the numbers for each one. I don't know if this is making sense. Look at these columns.

Test NumberCorrect NumberWrong Company User
1 8 1 A A1
1 6 3 A A2
1 5 4 B A3
2 6 3 C A1
2 8 2 A A1
2 6 4 A A2
3 8 7 B A1
3 6 8 C A2

For company "A" I want to figure out how many problems they got correct on test #1. I also want to figure out how many wrong, but if I can get the "correct" number I can get the "wrong number". Is it possible? Or should I say: how do I do it? Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.