Using braces with dynamic variable names in PHP

2018-12-31 02:24发布

I'm trying to use dynamic variable names (I'm not sure what they're actually called) But pretty much like this:

for($i=0; $i<=2; $i++) {
    $("file" . $i) = file($filelist[$i]);
}

var_dump($file0);

The return is null which tells me it's not working. I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research. $filelist is defined earlier on.

7条回答
冷夜・残月
2楼-- · 2018-12-31 02:30

i have a solution for dynamically created variable value and combined all value in a variable.

if($_SERVER['REQUEST_METHOD']=='POST'){
    $r=0;
    for($i=1; $i<=4; $i++){
        $a = $_POST['a'.$i];
        $r .= $a;
    }
    echo $r;
}
查看更多
谁念西风独自凉
3楼-- · 2018-12-31 02:41

Wrap them in {}:

${"file" . $i} = file($filelist[$i]);

Working Example


Using ${} is a way to create dynamic variables, simple example:

${'a' . 'b'} = 'hello there';
echo $ab; // hello there
查看更多
余生无你
4楼-- · 2018-12-31 02:41

I do this quite often on results returned from a query..

e.g.

// $MyQueryResult is an array of results from a query

foreach ($MyQueryResult as $key=>$value)
{
   ${$key}=$value;
}

Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']

Yep, it's probably lazy, but I've never had any problems.

查看更多
唯独是你
5楼-- · 2018-12-31 02:47

I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)

Note that the values for the position of the variable in the array go after the closing brace.

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];

查看更多
有味是清欢
6楼-- · 2018-12-31 02:49

Try using {} instead of ():

${"file".$i} = file($filelist[$i]);
查看更多
临风纵饮
7楼-- · 2018-12-31 02:49

Tom if you have existing array you can convert that array to object and use it like this:

$r = (object) $MyQueryResult;
echo $r->key;
查看更多
登录 后发表回答