开发者

Dynamically setting a variable in PHP?

So i want to deo something like this and not sure how

    for($s=0; $s < 5; $s++ ){
      $pre_config_query = "select * from preconfig where code = '{$industry_string}_{$s}_{$class_string}'";
      $pre_config_station = mysql_query($pre_config_query);
      $it_exists = mysql_num_rows($pre_config_station);
      if($it_exists>0){
        $pre_config = mysql_fetch_assoc($pre_config_station);
 开发者_运维技巧       $pre{$s} = $pre_config['id']; 

I want the end product to have these 5 variables named

    print $pre1;
    print $pre2;
    print $pre3;
    print $pre4;
    print $pre5;

That have the $pre_config['id'] if present....any ideas


You can use variable variables to accomplish that.

First, define a variable with the desired name:

$varname = "pre$s";

Second, assign a value to it:

$$varname = $pre_config['id'];

That's all!


this works but I'm not sure I'm answering your question.

<?php
for($s=1; $s < 6; $s++ ){
    $it_exists=1;
      if($it_exists > 0){
        $pre_config = array('id'=>rand(10,99));
        ${"pre".$s} = $pre_config['id'];
      }
}
echo $pre1."<br/>";
echo $pre2."<br/>";
echo $pre3."<br/>";
echo $pre4."<br/>";
echo $pre5."<br/>";

?>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜