遍历具有通用名称的变量 [英] Loop through variables with common name

查看:57
本文介绍了遍历具有通用名称的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

乍看之下,我认为您可以实现我想要做的事情.我想循环通过具有相同名称但带有数字前缀的变量.对于应该使用的循环类型,我也有些困惑,不确定"for"循环是否可以工作.唯一的事情是我无法确定php如何解释即时"或虚构变量.在输出带有美元符号的字符串时也会遇到麻烦.预先感谢!

At first glance I think you can get what I'm trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about the kind of loop I should use, not sure if a "for" loop would work. The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable. Ran into some trouble with outputting a string with a dollar sign as well. Thanks in advance!

$hello1 = "hello1";
$hello2 = "hello2";
$hello3 = "hello3";
$hello4 = "hello4";
$hello5 = "hello5";
$hello6 = "hello6";
$hello7 = "hello7";
$hello8 = "hello8";
$hello9 = "hello9";
$hello10 = "hello10";

for ( $counter = 1; $counter <= 10; $counter += 1) {
    echo $hello . $counter . "<br>";
}

推荐答案

尝试${"hello" . $counter}

$a = "hell";
$b = "o";
$hello = "world";
echo ${$a . $b};

// output: world

这篇关于遍历具有通用名称的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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