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][]

  • Your $params is not an array. Use array syntax to use $params[0] property – Sunil Pachlangia Aug 23 '16 at 10:04
  • 1
    @SunilPachlangia this syntax is correct since PHP 5.4. – roberto06 Aug 23 '16 at 10:07
  • Remove single quotes and add $ sign in $abc='params[0]'; – Sunil Pachlangia Aug 23 '16 at 10:10
  • I was edited question just now. But $abc is dynamically. So I cannot use this way. Anyway, thank @SunilPachlangia. – Hào Nghiêm Xuân Aug 23 '16 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. – Jakub Matczak Aug 23 '16 at 10:16

3 Answers3

2

use below way to access string

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

$new = $$abc;
echo $new[0];
AmmyTech
  • 738
  • 4
  • 10
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"
roberto06
  • 3,844
  • 1
  • 18
  • 29
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.

Afshan Shujat
  • 541
  • 4
  • 9