Reference an associative array from inside a string?

限于喜欢 提交于 2019-12-10 11:22:34

问题


"CREATE TABLE IF NOT EXISTS $tables[users]";

Works but..

"CREATE TABLE IF NOT EXISTS $tables['users']";

Does not.

I do not want to do this

$usersTable = $tables['users'];
"CREATE TABLE IF NOT EXISTS $usersTable";

I heard that it was considered bad practice to reference a key from an associative array without some sort of quotes around it. Is this true or is my first way of doing it preferred?


回答1:


You can do this with braces:

"CREATE TABLE IF NOT EXISTS {$tables['users']}";

Or through concatenation:

'CREATE TABLE IF NOT EXISTS ' . $tables['users'];



回答2:


You could do the folling:

$query = sprintf("CREATE TABLE IF NOT EXISTS %s", $tables['users']);

// do some other stuff



回答3:


You can use curly brackets.

"CREATE TABLE IF NOT EXISTS {$tables['users']}"; 


来源:https://stackoverflow.com/questions/5560718/reference-an-associative-array-from-inside-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!