在 for 循环内回显变量名称时获取变量值

发布于 2024-12-01 22:22:42 字数 514 浏览 1 评论 0原文

我正在学习,而且我已经被困在一些我认为太简单的事情上太久了,如果我是对的,抱歉。 请帮助我进化,这是我的问题:

我来自一个表格:

  $text1 = $_POST['TEXT1'];
  $text2 = $_POST['TEXT2'];
  $text3 = $_POST['TEXT3'];

现在我做:

 for ($n = 1; $n <= 3; $n++) {
 echo "Number " .$n. " is: " .$text.$n;
}

这是打印:

数字 1 是: 1

数字 2 是: 2

数字 3 是: 3

当我需要的是:

数字 1 是: $text1 Number 2 中包含的值

是: $text2

Number 3 中包含的值是: $text3 中包含的值

如何实现我所需要的?

多谢

I'm learning and I've been stuck for so long now with something I believe is too simple, sorry if I'm right.
Please help me to evolve, here's my question:

I have coming from a form:

  $text1 = $_POST['TEXT1'];
  $text2 = $_POST['TEXT2'];
  $text3 = $_POST['TEXT3'];

Now I do:

 for ($n = 1; $n <= 3; $n++) {
 echo "Number " .$n. " is: " .$text.$n;
}

This is printing:

Number 1 is: 1

Number 2 is: 2

Number 3 is: 3

When what I need is:

Number 1 is: value contained in $text1

Number 2 is: value contained in $text2

Number 3 is: value contained in $text3

How can achieve what I need?

Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沉鱼一梦 2024-12-08 22:22:42
for ($n = 1; $n <= 3; $n++) {
 $var = "text".$n;
 echo "Number " .$n. " is: " .$var;
}

但如果你将 POST 数据保存在一个数组中会更好,

你可以这样做:

$text = array();
$text[] = $_POST["TEXT1"];
$text[] = $_POST["TEXT2"];
$text[] = $_POST["TEXT3"];

然后你可以这样做:

for ($n = 1; $n <= count($text); $n++) {
 echo "Number " .$n. " is: " .$text[$n-1];
}
for ($n = 1; $n <= 3; $n++) {
 $var = "text".$n;
 echo "Number " .$n. " is: " .$var;
}

but it would be nicer if you save the POST data in an array

you can do it like this:

$text = array();
$text[] = $_POST["TEXT1"];
$text[] = $_POST["TEXT2"];
$text[] = $_POST["TEXT3"];

then you can do it like that:

for ($n = 1; $n <= count($text); $n++) {
 echo "Number " .$n. " is: " .$text[$n-1];
}
Hello爱情风 2024-12-08 22:22:42

使用这个:

for ($n = 1; $n <= 3; $n++) {
    echo "Number " .$n. " is: " . ${'text'.$n};
}

Use this:

for ($n = 1; $n <= 3; $n++) {
    echo "Number " .$n. " is: " . ${'text'.$n};
}
玩套路吗 2024-12-08 22:22:42

您可以将您的值放入数组中:

$texts = array($_POST['TEXT1'], $_POST['TEXT2'], $_POST['TEXT3']);

for ($n = 0; $n < count($texts); $n++) {
    echo "Number " . ($n+1) . " is: " . $texts[$n];
}

You could put your values into an array:

$texts = array($_POST['TEXT1'], $_POST['TEXT2'], $_POST['TEXT3']);

for ($n = 0; $n < count($texts); $n++) {
    echo "Number " . ($n+1) . " is: " . $texts[$n];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文