Reputation: 53
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][]
Upvotes: 0
Views: 1639
Reputation: 551
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.
Upvotes: 0
Reputation: 3864
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"
Upvotes: 2
Reputation: 738
use below way to access string
$params=[
'string'
];
$abc='params';
$new = $$abc;
echo $new[0];
Upvotes: 2