JohanStaart
JohanStaart

Reputation: 75

How to access numerically named variables generated by calling extract() on an indexed array?

I want a value of my array to be displayed if I use a equel or almost equel variable. So for example if I have the following array line: [1] => g I want to display 'g' if I use the variable $1 (Or even better with the varible $arr1, so it does not interfere with other things later on.)

Here is my code: (I'm uploading a simple .txt file with some letters and making a array of each individual charachter):

$linearray = array();
$workingarray = array();

while (!feof($file)) {
    $line = fgets($file);
    $line = str_split(trim("$line"));
    $linearray = array_merge($linearray, $line);
}

$workingarray[] = $linearray;

print_r($workingarray);

When I have done this I will get this outcome;

Array ( [0] => Array ( [0] => g [1] => g [2] => h [3] => o [4] => n [5] => d [6] => x [7] => s [8] => v [9] => i [10] => s [11] => h [12] => f [13] => g [14] => f [15] => h [16] => m [17] => a [18] => g [19] => i [20] => e [21] => d [22] => h [23] => v [24] => b [25] => v [26] => m [27] => d [28] => o [29] => m [30] => v [31] => b [32] => ) )

I tried using the following to make it work:

extract($workingarray);
echo "$1";

But that sadly doesn't work. I just recieve this:

$1

And I want to recieve this:

g

It would be even better if I recieved the same effect with for example echo "$arr1" and then recieve g and for echo "$arr2" recieve h etc.

Upvotes: 1

Views: 106

Answers (1)

Marc B
Marc B

Reputation: 360562

This is simply impossible: http://php.net/manual/en/language.variables.basics.php

Variable names cannot start with a digit. The only allowable first char for variable names are letters and underscore.

And don't use extract or similar constructs. All they do is litter your variable namespace with unpredictable/unknown junk - you could very easily overwrite some OTHER critical variable with this useless junk, making for very difficult/impossible bugs to diagnose.

You're not saving any time by making up these new variables.

Upvotes: 3

Related Questions