如何更改循环中的php变量名? [英] how to change php variable name in a loop?

查看:163
本文介绍了如何更改循环中的php变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为$ file的变量,for循环为:($ i = 1; $ i <= 5; $ i ++){}



对于for循环的每次迭代, $ i 值将被附加到 $ file 变量名,所以在for循环结束后,我应该有五个变量: $ file1 $ file2 $ file3 $ file4 $ file5

解决方案

使用 $ {'varname'}语法

$ p $ for($ i = 1; $ i <= 5; $ i ++){
$ {'file'。 $ i} = $ i;

$ / code>

然而,使用数组通常更好。

Lets say I have a variable called $file and the for loop: for($i=1; $i <= 5; $i++) {}

For each iteration of the for loop, the $i value will be appended to the $file variable name so after the for loop ends, I should have five variables: $file1, $file2, $file3, $file4, and $file5.

解决方案

Use ${'varname'} syntax:

for($i=1; $i <= 5; $i++) {
    ${'file' . $i} = $i;
}

However, it's often better to use arrays instead of this.

这篇关于如何更改循环中的php变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆