提问人:Kivennäisvesi 提问时间:12/16/2017 最后编辑:mickmackusaKivennäisvesi 更新时间:12/16/2017 访问量:77
PHP:如何在变量中增加一个同时包含文本和数字 [duplicate] 的数字
PHP: How to increase a number in variable that contains both text and the number [duplicate]
问:
这是一个非常愚蠢的问题。我想了解如何增加变量末尾的数字:
$Coffee1 = "black";
$Coffee2 = "brown";
$Coffee3 = "gray";
echo $Coffee1; => black
echo $Coffee1+1; => brown
echo $Coffee2+1; => gray
答:
0赞
B-GangsteR
12/16/2017
#1
以下是执行此操作的方法(代码):
<?php
$Coffee1 = "black";
$Coffee2 = "brown";
$Coffee3 = "gray";
$varName = "Coffee";
for($varIdx = 1; $varIdx <= 3; $varIdx++) {
echo "\n";
echo ${$varName . $varIdx};
}
但在这种情况下,最好使用数组而不是变量。
1赞
castis
12/16/2017
#2
你要找的机制是一个数组。
http://php.net/manual/en/language.types.array.php
$coffee = [
"black",
"brown",
"gray"
];
$index = 0;
echo $coffee[$index]; // "black"
echo $coffee[$index+1]; // "brown"
echo $coffee[$index+2]; // "gray"
这也是循环变得方便的地方。
foreach($coffee as $flavor) {
echo $flavor;
}
// "blackbrowngrey"
评论