admin 管理员组文章数量: 1086019
Is there any way through which I can declare the dynamic variable in php. for eg, I am using a for loop and the variable name is $message. and I want to add some dynamic data at the end of the variable name. code is below
foreach ($quant as $quantity) {
$message.$quantity['type'] = 'Listing ID : '.$quantity['product_id'].' With Quantity: '.$quantity['quantity'].'MT, State- '.$quantity['state_name'].' and Coal type-'.$quantity['coal_type'].'<br>';
}
so if the $quantity['type'] = 1, then the variable name should be $message1 and so on. currently I am trying to concatenate but it is wrong. Please tell me how it can be corrected. Thanks in advance
Is there any way through which I can declare the dynamic variable in php. for eg, I am using a for loop and the variable name is $message. and I want to add some dynamic data at the end of the variable name. code is below
foreach ($quant as $quantity) {
$message.$quantity['type'] = 'Listing ID : '.$quantity['product_id'].' With Quantity: '.$quantity['quantity'].'MT, State- '.$quantity['state_name'].' and Coal type-'.$quantity['coal_type'].'<br>';
}
so if the $quantity['type'] = 1, then the variable name should be $message1 and so on. currently I am trying to concatenate but it is wrong. Please tell me how it can be corrected. Thanks in advance
Share Improve this question asked May 2, 2017 at 11:17 Nikhil GuptaNikhil Gupta 1112 bronze badges2 Answers
Reset to default 0Your own solution works I guess (double $$) but usually you do it this way:
$quantity['type'] = 1;
${'message' . $quantity['type']} = 'hello';
echo $message1; // hello
After doing a little research I found out the solution myself.
following is the code showing how it can be done
foreach ( $quant as $quantity ) {
$test = 'message' . $quantity['type'];
$test .= 'Listing ID : ' . $quantity['product_id']
. ' With Quantity: ' . $quantity['quantity']
. 'MT, State- ' . $quantity['state_name']
. ' and Coal type-' . $quantity['coal_type'];
}
Now $message1 will print the result.
本文标签: php Creating a dynamic variable
版权声明:本文标题:PHP, Creating a dynamic variable 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1736271992a1730433.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论