0

If I have:

<?php
$params=[
    [
        'string'
    ]
];
//params get from $this->params()->fromPost();
$abc='params[0][0]';//$abc dynamiccly

I cannot access $params[0]

How to get string element?

I try to use

echo $$abc;

But

Notice: Undefined variable params[0][]

5
  • Your $params is not an array. Use array syntax to use $params[0] property Commented Aug 23, 2016 at 10:04
  • 1
    @SunilPachlangia this syntax is correct since PHP 5.4. Commented Aug 23, 2016 at 10:07
  • Remove single quotes and add $ sign in $abc='params[0]'; Commented Aug 23, 2016 at 10:10
  • I was edited question just now. But $abc is dynamically. So I cannot use this way. Anyway, thank @SunilPachlangia. Commented Aug 23, 2016 at 10:13
  • Basically you can't do that directly as you're trying. You have two options. First is to parse $abc string to get separately variable name and index value (e.g. as roberto06 showed in his answer), but that's not efficient to do so much work only to get variable's value. I would suggest (if possible) to change your data flow design which is in this case the incoming value from POST. Commented Aug 23, 2016 at 10:16

3 Answers 3

2

If $abc is defined dynamically, you have to split it in two variables : $arrayName and $arrayKey, as such :

$params = array('string');
$abc = 'params[0]';
$arrayName = substr($abc,0,strpos($abc,'['));
$arrayIndex = preg_replace('/[^\d\s]/', '',$abc);
echo ${$arrayName}[$arrayIndex]; // returns "string"
Sign up to request clarification or add additional context in comments.

1 Comment

You have defined the variable dynamically, you can access the value using loop -
2

use below way to access string

$params=[
    'string'
];
$abc='params';

$new = $$abc;
echo $new[0];

Comments

0

For accessing the values of dynamic varible you can execute a loop-

<?php
$params=[
    'string'
];
$abc= 'params';

foreach($$abc as $k=>$v){
    echo $v;
}

?>

If you want to access it directly by index so you need to reassign the dynamic variable in another variable like $newArr = $$abc and then access $newArr.

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.