如何在PHP中使用for循环打印$ title1 $ title2 $ title3 ... [英] How can I print $title1 $title2 $title3... using a for loop in PHP

查看:114
本文介绍了如何在PHP中使用for循环打印$ title1 $ title2 $ title3 ...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用for循环打印这些变量:

I want to print these variables using a for loop:

<?php
$title1 = "TEXT1";
$title2 = "TEXT2";
$title3 = "TEXT3";
$title4 = "TEXT4";
$title5 = "TEXT5";

for ($i = 1; $i <= 10; $i++) {    
  echo "$title".$i;   // I want this: TEXT1 TEXT2 TEXT3 TEXT4 TEXT5
}
?>

推荐答案

要完全执行所需的操作,请创建一个包含要使用的变量名称的新变量,然后将其用作变量变量,如下所示:

To do exactly what you want, create a new variable containing the name of the variable you want to use, and then use it as a variable variable, like this:

$varname = "title$i";
echo $$varname;

但是,更正确的方法是使用数组,而不是十个不同的变量.

However, the more correct way to do this is to use an array, instead of ten different variables.

$titles = array(
    "TEXT1",
    "TEXT2",
    "TEXT3",
    "TEXT4",
    "TEXT5"
);

for ($i = 0; $i < count($titles) - 1; $i++) { // notice that we're starting at 0 instead of 1
    echo $title[$i];
}

这更快,更干净并且通常可以更安全.

This is faster, cleaner and can often be more secure.

这篇关于如何在PHP中使用for循环打印$ title1 $ title2 $ title3 ...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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