-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

3

2 Answers 2

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,

Sign up to request clarification or add additional context in comments.

1 Comment

The $reqvar is needed to be dynamic
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.