-1

I have the following example data array:

$data = [];
$data["general"]["login"] = "Auth"
$data["general"]["login_failed"]["err1"] = "First error"

and the following request var:

$reqvar = "['general']['login']";

I'd like to:

print_r($data{$reqvar});

which would translate as

print_r($data['general']['login']);

but it doesn't seems to work

I'm not willing to iterate over the full array, it doesn't make sense considering that I know the path of the value that I want to print.

Thank you

user3405598
  • 85
  • 1
  • 7
  • its working only you have to add semi-colon (;) example - $data["general"]["login"] = "Auth"; – shubham715 Sep 26 '16 at 11:12
  • Possible duplicate of [How to reffer dynamically to a php ARRAY variable(s)?](http://stackoverflow.com/questions/7850744/how-to-reffer-dynamically-to-a-php-array-variables) – Gectou4 Sep 26 '16 at 11:21
  • I've found the solution > http://stackoverflow.com/questions/9628176/using-a-string-path-to-set-nested-array-data/36042293#36042293 – user3405598 Sep 26 '16 at 13:02

2 Answers2

1

First of all take a look on PHP documentation - Arrays:

"Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above)."

So I think you are trying something like that:

<?php

$data = [];
$data["general"]["login"] = "Auth";
$data["general"]["login_failed"]["err1"] = "First error";

$reqvar1 = 'general';
$reqvar2 = 'login';

print_r($data{$reqvar1}{$reqvar2});

I strongly suggest you to refactor your code. Take a look on:

Regards,

-1

Translate both values to dot notation and then you can select item into array. For example

$data["general"]["login"] = "Auth";
$data["general"]["login_failed"]["err1"] = "First error";
$data = convertToDotNotaion($data);
// it should looks like
$data["general.login"] = "Auth";
$data["general.login_failed"]["err1"] = "First error";

Then convert your came same way. And you can access to value use next code:

$data[$reqvarConverted}]

This is function convertToDotNotaion you should implement it yourself

Eugene
  • 1,690
  • 3
  • 16
  • 30