开发者

Multiple Variable Variables in PHP

I am fairly new to PHP and programming in general... I am attempting to use a foreach loop to set some options on a page I have created. It all works except for the last section, where I am attempting to assign variables dynamically, so I can use them outside the loop.

<?PHP

$array=array(foo, bar, baz);

foreach ($array as $option) {

  // I have if statements to determine what $option_req 
  // and $option_status end up being, they work correctly.

  $option_req="Hello";
  开发者_StackOverflow社区$option_status="World";

  $rh='Req_';
  $sh='Status_';

  $$rh.$$option=$option_req;
  $$sh.$$option=$option_status;

  }

echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;

?>

When the loop is finished, should this now give me six variables?

$Req_foo
$Status_foo

$Req_bar
$Status_bar

$Req_baz
$Status_baz

I have played with this a bit, searches on Google seem fruitless today.


To access some array item, just access some array item.
No loops required.

$req = array("foo" => 1, 
             "bar" => 2, 
             "baz" => 3,
             );
echo $req['foo'];

plain and simple


Looks like PHP doesn't like the concatenation when you're trying to do an assignment. Try doing so beforehand, like so:

<?php

$array = array('foo', 'bar', 'baz');

foreach ($array as $option) 
{
    $option_req="Hello";
    $option_status="World";

    $rh = 'Req_';
    $sh = 'Status_';

    $r_opt = $rh.$option;
    $s_opt = $sh.$option;

    $$r_opt = $option_req;
    $$s_opt = $option_status;
}

echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;

As other commenters suggested, this isn't a great practice. Try storing your data in an array, rather than just cluttering up your namespace with variables.


You could (though you should not!) do:

${$rh.$option} = ...


Variable variables don't work that way. You need to have one variable containing the string.

$opt_r = $rh.$option;
$$opt_r = $option_req;

$opt_s = $sh.$option;
$$opt_s = $option_status;

Also, make sure to quote your strings:

$array=array('foo', 'bar', 'baz');

I don't suggest using variable variables, but if you want to, this is how to do it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜