0

I have a variable defined as an array, which is built in a loop:

$years=array("2010","2011","2012");

    foreach($years as $year)
    {
    ///an SQL query + some PDO that queries a different table based on $year
    $dataset_full_{$year} = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

so you end up with a set of arrays named

$dataset_full_2010
$dataset_full_2011
$dataset_full_2012

when I print_r($dataset_full_2012); however I get nothing, but if I go ahead and define

$current_year="2012";

then

print_r($dataset_full_{$current_year});

I get my array. What piece of syntax am I misusing here?

Thanks in advance

1 Answer 1

1

To be safe, you can always use an intermediate string:

$var_name = "dataset_full_" . $year;
$$var_name = $stmt->fetchAll(PDO::FETCH_ASSOC);

You can also use concatenation within curly braces:

${"dataset_full_" . $year} = ...

Here's the docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.