0

I have a function which receives unlimited number of arguments. (I am using func_get_args for that)

Example: function generate($one, $two, $three, ...)

Each one of the parameters represents a column in another array (let's call it $array).

I want to receive the value of the another array on $array[$one][$two][$three]

That means that the number of "[]" is unlimited

I have tried to generate a var in var for this.

<?php

  $ron = array("sir" => "yes");
  $name = 'ron["sir"]';
  echo var_dump(${$name});
?>

My result:

Notice: Undefined variable: ron["sir"] in C:\Users\ronr\Desktop\xampp\htdocs\lol.php on line 5 NULL

2

2 Answers 2

1

If you want to use the args as a path to array value, you can try this:

$result = $array;
$args = func_get_args();

foreach($args as $arg) {
  $result = $result[$arg];
}

var_dump($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Ive thought about something similar but didn't think It is the right way. Thank you very much!
1

Actually, the error is correct, you are defining a variable named ron["sir"], something like this:

${'ron["sir"]'} = 'foobar';
echo ${'ron["sir"]'};

. To show the value of sir in the $ron array, it should be:

$ron = array("sir" => "yes");
$name = 'ron';
var_dump(${$name}["sir"]);

5 Comments

Hi, Thank you for trying to help. Please read the rest of my question. Thanks again
...read the rest of my question... What exactly do you mean? @RonRofe
If we have 4 arguments in the function - "hello", "its", "me", "here" ----- So I want to receive the value of the array on $array["hello"]["its"]["me"]["here"]
I suppose the real question is "can I use an interpolation to access to an array"
@RonRofe what if the index does not exists? what will happen then?

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.