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

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

问题描述

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

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

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

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.

推荐答案

使用 ${'varname'}语法:

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

但是,使用数组通常比使用数组更好.

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

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

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