php: accessing array dynamically using a string variable - php

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"];

Related

Unable to get dynamic PHP's Object value using PHP variable

PHP is unable to get the value for dynamic object prepared as:
$abc->{$dynamic_object_pattern}
Where the value of the variable $dynamic_object_pattern is, json->{'data_1'}->{'value'}
For me, PHP 7.1 is understanding the statically defined pattern like below, and fetching the value as it should:
$abc->json->{'data_1'}->{'value'}
But not when I put the whole portion into a variable and then try to get its value. I Tried,
$abc->{$dynamic_object_pattern} and $abc->$dynamic_object_pattern
both ways, but no solution yet.
The error comes is Notice: Undefined property: stdClass::$json->{'data_1'}->{'value'}
I'm attempting an answer without seeing your JSON data
Here you say :
But not when I put the whole portion into a variable and then try to
get its value
From that line alone it sounds like you are trying to get value from a string rather than array. If you put the whole portion into a variable, PHP will interpret it as string. Make sure you add array() before newly created variable.
Natural array :
$array = array();
Now a string
$variable = $array;
Convert string to array
$new_array = array($variable);
Also, have you tried decoding?
// decode
$response = json_decode($new_array, true);
//print out
var_export(array_unique(array($response)));

index of array with smarty variables is not working

I have created array variable in .php file
like
$arImagePath[TE] = 'XYZ';
in my .tpl
{$carnumber} is giving 'T' and {$carinitial} is giving 'E'.
I am trying to get value 'XYZ' as follows
{$arImagePath[{$carnumber}+{$carinitial}]}
I tried many combination still unavailable to get array value.
smarty version -2.6.26
Hoping for any help.
From documentation (Smarty v2) :
{$foo[bar]} <-- syntax only valid in a section loop, see {section}
So, if you want to access the array variable directly and you are not in a loop, you have to do it this way:
{$foo.bar} <-- display the "bar" key value of an array, similar to
PHP $foo['bar']
Now, to archive what you need:
// This assignment could change dynamically
{assing var="carnumber" value="T"}
{assing var="carinitial" value="E"}
// For the sake of clarity, I'm going to concat in one variable the above assignments
{assing var="index" value=$carnumber|cat:$carinitial}
//Now access the array at the index we need
{$arImagePath.$index} // XYZ

Issue with using extract() PHP

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

php get array elememnt using $$

i know this
$var1 = "10";
$var2 = "var1";
then
echo $$var2 gives us 10
i want to this with array
i have array
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
i have some logic that will pick one array from set of array , all array will look like $intake_arr
if i do this $target_arr = "intake_arr";
then can $$target_arr[5] will yield 10? i tried but i didnt that 10 value, how can i achieve this with array
Your statement ($$target_arr[5]) is ambiguous. PHP doesn't know what you actually want to say: Do you mean: use $target_arr[5]'s value and prepend the $, to use that as a variable, or do you want to use the value of $target_arr, and get the fifth element of that array?
Obviously it's the latter, but PHP doesn't know that. In order to disambiguate your statement, you have to use curly braces:
${$target_arr}[5];
That'll yield 10. See the manual on variable variables for details
Note:
As people said in comments, and deleted answers: variable variables, like the one you're using is risky business. 9/10 it can, and indeed should be avoided. It makes your code harder to read, more error prone and, in combination with the those two major disadvantages, this is the killer: it makes your code incredibly hard to debug.
If this is just a technical exercise, consider this note a piece of friendly advice. If you've gotten this from some sort of tutorial/blog or other type of online resource: never visit that site again.
If you're actually working on a piece of code, and you've decided to tackle a specific problem using variable vars, then perhaps post your code on code-review, and let me know, I'll have a look and try to offer some constructive criticism to help you on your way, towards a better solution.
Since what you're actually trying to do is copying an array into another variable, then that's quite easy. PHP offers a variety of ways to do that:
Copy by assignment:
PHP copies arrays on assignment, by default, so that means that:
$someArray = range(1,10);//[1,2,3,4,5,6,7,8,9,10]
$foo = $someArray;
Assigns a copy of $someArray to the variable $foo:
echo $foo[0], ' === ', $someArray[0];//echoes 1 === 1
$foo[0] += 123;
echo $foo[0], ' != ', $someArray[0];//echoes 123 != 1
I can change the value of one of the array's elements without that affecting the original array, because it was copied.
There is a risk to this, as you start working with JSON encoded data, chances are that you'll end up with something like:
$obj = json_decode($string);
echo get_class($obj));//echoes stdClass, you have an object
Objects are, by default, passed and assigned by reference, which means that:
$obj = new stdClass;
$obj->some_property = 'foobar';
$foo = $obj;
$foo->some_property .= '2';
echo $obj->some_property;//echoes foobar2!
Change a property through $foo, and the $obj object will change, too. Simply because they both reference exactly the same object.
Slice the array:
A more common way for front-end developers (mainly, I think, stemming from a JS habbit) is to use array_slice, which guarantees to return a copy of the array. with the added perk that you can specify how many of the elements you'll be needing in your copy:
$someArray = range(1,100);//"large" array
$foo = array_slice($someArray, 0);//copy from index 0 to the end
$bar = array_slice($someArray, -10);//copy last 10 elements
$chunk = array_slice($someArray, 20, 4);//start at index 20, copy 4 elements
If you don't want to copy the array, but rather extract a section out of the original you can splice the array (as in split + slice):
$extract = array_splice($someArray, 0, 10);
echo count($someArray);//echoes 90
This removes the first 10 elements from the original array, and assigns them to $extract
Spend some time browsing the countless (well, about a hundred) array functions PHP offers.
${$target_arr}[5]
PHP: Variable variables
Try this one:
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
$target_arr = 'intake_arr';
print ${$target_arr}[5]; //it gives 10
For a simple variable, braces are optional.But when you will use a array element, you must use braces; e.g.: ${$target_arr}[5];.As a standard, braces are used if variable interpolation is used, instead of concatenation.Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate.Take a look here for php variable variables http://php.net/manual/en/language.variables.variable.php

Variable in $_POST returns as string instead of array

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];

Categories