0

I'm having a trouble getting my array content when using a declared variable as my array indexes shown below.

$indexes = "[0][1][0][1]";
$code = $params["smv_code"].$indexes;

this returns an "Array to string conversion error";

Note that the $indexes is dynamic depends on the "parent_0_1_0_1" params content of the array index.

8
  • this is very unclear, what exactly are you trying to do, and what are thinking your code should be doing? Aug 29, 2017 at 2:38
  • It is very clear what he wants to do - he is trying to navigate through the multi-dimensional array using code notation. Aug 29, 2017 at 2:43
  • except he's not... what value is he actually looking for? the value of parent_0_1_0_1 or the value of $params['smv_code'][0][1][0][1] Aug 29, 2017 at 2:46
  • you're right... I didn't open the image... parent_0_1_0_1 is an array itself with 0 => LVL2??? Aug 29, 2017 at 2:50
  • exactly making your answer irrelevant and this question nonsense as is Aug 29, 2017 at 2:50

1 Answer 1

1

the . operator just does a string concatenation - it's not going to work for code like that. I don't think PHP has the ability to interpret raw code like that - at least not safely. (You can always use eval, but there are serious security concerns for using something like that - injection, etc.).

I would suggest just traversing the array "manually" through interpreting the indexes yourself. Change the $indexes to "0,1,0,1" and do the following:

$index_array = explode(',',$indexes)
$code = $params["smv_code"];
foreach($index_array as $i) {
  $code=$code[$i];
}

$code at the end should be the value you're looking for.

2
  • this solves my problem, just want to ask if it try to cast the params to (object) and make the $indexes "->0->1->0->1" and tried this one $params->smv_code{$indexes} will this be possible? Aug 29, 2017 at 2:54
  • Nope, PHP isn't dynamic like that. Sorry. As mentioned before, the only way (as far as I know) is to use the eval() function like Wizard posted in the comment... but then you can open yourself to exploits if they can craft the param properly to run other code. Aug 29, 2017 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.