php - 在PHP中,如何在两个变量名之间添加下划线

标签 php string

我有一些数据库字段叫做

picture1_en
picture2_en
...
picture1_de
picture2_de
...
picture1_it
picture2_it

是的,它可以用另一种方式实现,但我不能改变实现方式。

假设我有一个名为 $lang 的变量,其中包含“de”或“en”或“it”
现在,如果我想打印这个值,我可以使用这个:

for($i=1; $i<=10; ++$i)
  echo $r["picture$i_$lang"];

问题是 PHP 将下划线解释为变量名的一部分(例如,它将其解释为“$i_”)。我尝试了很多疯狂的方法来转义下划线,但都没有用。

当然可以

echo $r["picture".$i."_".$lang];

但我想知道是否有办法强制 PHP 将“_”解释为字符串文字,而不是变量名的一部分。

最佳答案

您可以使用花括号分隔字符串中的变量名边界(仅限双引号)

$r["picture{$i}_{$lang}"];

$r["picture${i}_${lang}"];

http://php.net/manual/en/language.types.string.php

复杂( curl )语法

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

关于php - 在PHP中,如何在两个变量名之间添加下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805883/

相关文章:

c++ - 将 getline() 字符串拆分为多个 int 和 char 变量?

php - mysql 结果总数未正确显示

php - 从 php 自动保存到 mysql,无需页面更改或提交按钮

php - 为什么我的 <select> 值没有发布在电子邮件中

php - 从 mysql 获取数组创建命名 session 数组

ios - 使用 Swift 的双重格式

android - 如何在android中增加strings.xml中的字体大小

php - 向 Blade 中的日期字段添加三个小时

javascript - Coffeescript 将文本文件的内容加载到字符串变量中

c - c中的strcmp字符串和字符数组