How to make a "reference" to an array by string in php

Viewed 53

I have a problem which I'm unable to solve (in an easy way) at the moment:

$clients = array("A", "B");

$array_data_A = array(
    array("1000733", "1.6.0"),
    array("1000733", "1.8.0"),
    array("1000733", "1.8.1"),
    array("1000733", "1.8.2"),
    array("1000733", "1.8.3"),
    array("1000733", "1.8.4"),
);

$array_data_B = array(
    array("1000733", "1.6.0"),
    array("1000733", "1.8.0"),
    array("1000733", "1.8.1"),
    array("1000733", "1.8.2"),
    array("1000733", "1.8.3"),
    array("1000733", "1.8.4"),
);

Now I can make this:

foreach ($clients as $client) {

    // won't work
    $data_array = '$array_data'.$client;
    getsqldata($client, $data_array);

    // works
    switch ($client) {
        case "A":
            getsqldata($client, $array_data_A);
            break;
    }
}       

Is it the only way to solve this with a case function? Or is there a possibility to store a string in a variable which can be used as a reference to the correct array?

Because I have many clients (50+) I'm searching for a dynamic way to solve this...

2 Answers

You were missing few things one of them is _ with in the string.

Try sample code here

Change this to:

$data_array = '$array_data'.$client;

This:

$data_array = ${'array_data_' . $client};

You can achieve this by using following code:

$str = "array_data_".$client;
$data_array = $$str;

Here is the documentation.

Related