I have dynamically created an array and I want to extract the array and put each item into its own variable.
Here's my PHP:
$bar = $_POST['foo'];
extract($bar);
echo $1;
foo is an array from a form I made.
Whenever I run the script I get this error:
Parse error: syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '$' in /Application/...
When I change my code to:
$bar = $_POST['foo'];
extract($bar, EXTR_PREFIX_ALL, "bar_");
echo $bar_1;
I get the undefined variable error.
Please help me.
UPDATE:
My first code was informational, another person might come across this question with that problem not knowing what's wrong. The second piece of code is my actual code.
M intention is to input each array item into a different field in a mysql table. I haven't written the full code yet since this extract() thing doesn't seem to be working.
UPDATE 2:
$_POST['foo'] is an array of checkbox values
Variables in PHP cannot start with numbers:
echo $1;
That's invalid and will throw an error.
You're also using extract improperly in that you're using it on something that may or may not be an array. We have no guarantee that $_POST['foo'] is an associative array(and it's not), which is the only array type extract works on. extract uses the keys from the associative array to create the new variables.
$bar = $_POST['foo'];
extract($bar, EXTR_PREFIX_ALL, "bar_");
echo $bar_1;
From http://php.net/extract
Prefixes are automatically separated from the array key by an underscore character.
Your extracted variable is named $bar__1 (two underscores).
But listen to everyone who answered, "do not use extract() on untrusted data."
This is very unsafe.
You should not do it.
foreach($_POST['foo'] as $key=>$value) {
${"itemnumber".(string)$key} = $value;
}
Now you can acces $itemnumber2 ---> equals to the array item in the position 2
EDIT: I just tested it at writecodeonline.com and it works:
$arr = array('one', 'two');
foreach($arr as $key=>$value) {
${"itemnumber".(string)$key} = $value;
}
echo $itemnumber1; //echoes: two
Here you can see a similar case:
http://us2.php.net/manual/en/function.extract.php#60946
Related
Its like this
I have a variable that has an array index in it, for e.g.
$var = 'testVar["abc"][0]';
or
$var = 'testVar["xyz"][0]["abc"]';
or it could be anything at run time.
Now when I try to access this by using this php code:
echo $$var;
or
echo ${$var};
I get a warning saying Illegal offset at line ...
but if I use this code, it works
eval('echo $'.$var);
I do not want to use eval(). Is there any other way?
EDIT:
The variable $testVar is an array build up on runtime and it could have multi-dimensional array built dynamically. Its format is not fixed and only the script knows by the use of certain variables that what the array could be.
for e.g. at any point, the array might have an index $["xyz"][0]["abc"] which I want to access dynamically.
My php version is 5.1
According to the documentation, what you are trying to accomplish is not possible:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
In your case, $$var tries to read a variable with the name testVar["xyz"][0]["abc"], and not indexing an array. You could dereference that array like this:
$a = "testVar";
echo ${$a}["xyz"][0]["abc"];
I couldn't find any useful examples or help online via google search, and the solution should be simple, but the results are not what I'm expecting.
I have 3 arrays - to list a few:
$A = array(1,0,1,1,1,0,1,1,1);
$B = array(1,1,1,0,1,0,1,0,1);
$C = array(1,1,1,0,1,0,1,1,1,0,1);
And then I wanted to create an array where the elements would be [0]-[2] referencing each of the 3 arrays mentioned above. The declaration for that is:
$LETTERS= array($A,$B,$C);
I'm trying to get the elements of $A[x] with this code:
$LETTERS[0][0];
But the problem is that it outputs: Array[0] instead of 1
If I echo $A[0] the output will be 1 as expected.
So what am I doing wrong? I don't think there is a problem with reserved words &| using uppercase letters as variables, is there?
How can I access data in this 2-dimensional array?
Thanks in advance for any help.
EDIT
The problem was that I was trying to echo the output with this code:
echo "element [0][0]: $LETTERS[0][0]";
For some reason, this wont work. I needed to keep out everything except the actual variable. Anyone know why that's the case?
You need to re-check your code.
echo $LETTERS[0][0];
outputs 1
edited question answer
echo "element [0][0]: {$LETTERS[0][0]}";
Works here:
php > $A = array(1,0,1,1,1,0,1,1,1);
php > $B = array(1,1,1,0,1,0,1,0,1);
php > $C = array(1,1,1,0,1,0,1,1,1,0,1);
php > $LETTERS= array($A,$B,$C);
php > echo $LETTERS[0][0];
1
ok, given your edit... PHP's interpreter isn't greedy. It will not pull in multiple array dimensions when you embed that multidimensional array in a string. e.g
echo "$arr[0][0]"
is seen as
echo "$arr[0]", "[0]"
^^^^--arrray
^^^-random string
Doing echo $array forces the array into string context, but PHP will not dump the array's contents, it will simply print out Array, which is why you got Array[0].
To force PHP to see the entire array reference, you need to use the {} notation:
echo "{$arr[0][0]}";
which will properly handle the extra array dimensions.
Incidentally, this is also useful for objects-in-strings, e.g.
echo "$obj->attribute->attribute"
is better written as
echo "{$obj->attribute->attribute}"
That code is working correctly. Live demo here.
EDIT: After your edition, the correct way to do that would be:
echo "element [0][0]: {$LETTERS[0][0]}";
That way PHP will expand your variable properly.
I have this array:
$array = array();
$array['123'] = 'abc';
$array['456'] = 'def';
Now I would like to get data from that array based on a variable. This is what I tried:
$variable = '123';
$result = $array[$variable];
echo $result;
It appears to be wrong, but i don't know why. It results in a warning:
Illegal offset type […]
I ran that exact code into my compiler and it worked; possibly it is a white-space error (random characters you cant see but still cause bugs). I would try to physically retype that section of code and delete the old one.
I would suggest trying this to make sure the variable is cast as a string:
$result = $array[(string)$variable];
That's most likely your problem. I think maybe $post['id'] is either mistakenly a multi-dimensional array or somehow becoming an object of a type not accepted as an array key.
In my form i have fields with name photoid[] so that when sent they will automatically be in an array when php accesses them.
The script has been working fine for quite some time until a couple days ago. And as far as i can remember i havent changed any php settings in the ini file and havent changed the script at all.
when i try to retrieve the array using $_POST['photoid'] it returns a string with the contents 'ARRAY', but if i access it using $_REQUEST['photoid'] it returns it correctly as an array. Is there some php setting that would make this occur? As i said i dont remember changing any php settings lately to cause this but i might be mistaken, or is there something else i am missing.
I had the same problem. When I should recieve array via $_POST, but var_dump sad: 'string(5) "Array"'. I found this happens, when you try use trim() on that array!
Double check your code, be sure you're not doing anything else with $_POST!
Raise your error_reporting level to find any potential source. It's most likely that you are just using it wrong in your code. But it's also possible that your $_POST array was mangled, but $_REQUEST left untouched.
// for example an escaping feature like this might bork it
$_POST = array_map("htmlentities", $_POST);
// your case looks like "strtoupper" even
To determine if your $_POST array really just contains a string where you expected an array, execute following at the beginning of your script:
var_dump($_POST);
And following for a comparison:
var_dump(array_diff($_REQUEST, $_POST));
Then verifiy that you are really using foreach on both arrays:
foreach ($_POST["photoid"] as $id) { print $id; }
If you use an array in a string context then you'll get "Array". Use it in an array context instead.
$arr = Array('foo', 42);
echo $arr."\n";
echo $arr[0]."\n";
Array
foo
$_POST['photoid'] is still an array. Just assign it to a variable, and then treat it like an array. ie: $array = $_POST['photoid'];
echo $array[0];
I found this PHP code in an app I have to modify...
$links = mysql_query($querystring);
foreach (mysql_fetch_array($links) as $key=>$value)
{
$$key = $value;
}
I'm a bit stumped.
Is it really iterating over the query results and copying the value into the key?
If so, what would be the point of this?
Also, what is the double $$ notation? I've not seen this before in PHP and I can't seem to find reference to it on the PHP site. Is it a typo? It doesn't seem to be affecting the code. I don't want to go "fixing" anything like this without understanding the consequences.
The $$ isn't a typo; it's how you interact with a variable named by another variable. Like if you do
$varname = 'foo';
$$varname = 'bar';
you've just set $foo to 'bar'.
What the loop is doing is expanding the row contents into the current variable namespace, kind of like extract(). It's a terrible way to do it, not least because it's also iterating over the numeric indices.
You generally see that written like this.
$links = mysql_query($querystring);
while ($row = mysql_fetch_array($links))
{
echo $row['id'];
}
The $$ is what's called a variable variable.
It looks like it's essentially making the keys as vars holding the value. Sort of what register_globals does to the POST/GET etc vars. I wouldn't recommend doing it this way. I dare say it will lead to problems, like overwriting vars, and unexpected vars being available.
It's creating key-value pairs based on the sql query results and result structure.
As for the $$, it's just another variable, except this time it's the result that's set to a variable.
$key = "hello";
$$key = "hi";
echo $key;
output is: "hi"
The $$ will reference the variable with the name stored in the first variable. So for example:
$var='some';
$some=15;
echo $$var;
That will print 15. It takes $vara and gets 'some', so then it takes that as a variable name because of the second $ and it prints the value of $some which is 15.
So basically that code is copying the values into a variable that has the same name as the key.